jashkenas / coffeescript

Unfancy JavaScript
https://coffeescript.org/
MIT License
16.52k stars 1.98k forks source link

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

Closed emk closed 14 years ago

emk commented 14 years ago

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 commented 14 years ago

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 commented 14 years ago

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:

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;
}