Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Indenting 'else' after 'switch' and 'if' #697

Closed
emk opened this issue Sep 20, 2010 · 2 comments
Closed

Indenting 'else' after 'switch' and 'if' #697

emk opened this issue Sep 20, 2010 · 2 comments

Comments

@emk
Copy link

emk commented Sep 20, 2010

There's an interesting inconsistency with how 'else' is indented in 'switch' and 'if' statements:

# Here's the syntax for 'if'. The 'else' is flush with the headword.
if day is "Tue"
  go relax
else
  go work

# Here's the syntax for 'switch'. The 'when' and 'else' must be indented.
switch day
  when "Tue"
    go relax
  else
    go work

If I try to keep 'when' flush with 'switch', I get:

Error: In stdio, Parse error on line 122: Unexpected 'TERMINATOR'

Here are the equivalent constructs in Ruby:

if day == "Tue"
  go relax
else
  go work
end

case day
when "Tue"
  go relax
else
  go work
end

jashkenas suggested changing CoffeeScript to use the Ruby indentation by default. He asked whether it would be desirable to support the existing CoffeeScript indentation rules as well.

@jashkenas
Copy link
Owner

We talked about this a little in #coffeescript, and I think we're going to stick to the indentation that we've currently got -- the reason being that it mirrors JavaScript's use of curly braces to delimit the statements...

if (a) {
  b;
} else {
  c;
}

And:

switch (a) {
  case b:
    c;
}

@emk
Copy link
Author

emk commented Sep 21, 2010

Interesting! I always indent my JavaScript as:

switch (a) {
case b:
   c;
}

Just to make sure, I checked a number of style guides. Here's Crockford's JavaScript style guide:

switch Statement

A switch statement should have the following form:

switch (expression) {
case expression:
    statements
default:
    statements
}

Each case is aligned with the switch. This avoids over-indentation.

Each group of statements (except the default) should end with break, return, or throw. Do not fall through.

Other style guides which place 'case' flush with the braces, include Sun's Java style guide.

Projects which indent 'case' statements include some very high-profile JavaScript projects:

  • jQuery & jQueryUI
  • SproutCore

And the SpiderMonkey C style guide uses half an indentation level, just to be strange. :-)

So I would say that the JavaScript community uses both forms:

switch (a) {
  case b:
    c;
}


switch (a) {
case b:
  c;
}

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants