javascript: Multi-line if statements - breaks and indentation
I think it would be nice to add an additional section to the guide for multi-line if statements, especially where to set breaks and how the indentation should look like? I have added some examples below and would like to know what your preferred way of formatting this is.
Example:
if (a === 123 && b === 'abc') {
doSomething();
}
Case A: Breaks are applied after logical operators.
if (a === 123 &&
b === 'abc') {
doSomething();
}
Case B: Breaks are applied before logical operators.
if (a === 123
&& b === 'abc') {
doSomething();
}
Indentation: Regardless of where the breaks are set, indent the next line with 4 instead of 2 spaces.
// Case A
if (a === 123 &&
b === 'abc') {
doSomething();
}
// Case B
if (a === 123
&& b === 'abc') {
doSomething();
}
I personally prefer Case B because you can immediately see what’s going on, but I’m not sure about the indentation - would still prefer 2 over 4 though as putting the operators in front of it help a little bit to distinguish the statement from the block.
At this point I also want to say that this guide is super useful, so thanks a lot for sharing this!
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 16 (1 by maintainers)
Neither.
Only one of these two is acceptable:
We’re not decided yet, nor do we enforce, whether the operator should end lines or begin them.
A PR to the guide that adds a section on this would be appreciated.
I vote for this:
Simply because you can easily comment out a condition if you are debugging like so:
How about this idea?
This makes absolutely no difference of course 😃
With operators at the beginning you can comment out any line, apart from the first one, With operators at the end you can comment out any line, except the last one.
Whilst true, most of the time you are commenting out conditions added after the initial.
Putting the operator on its own line certainly avoids the question of “before” or “after”, but I think it would end up making long conditionals have a lot of vertical height, sacrificing readability.
Huh, that came kind of unexpected, but thanks for the answer! At least I don’t have to look for “bad” examples anymore then 😃! Will create one in the next days.
For anyone who stumbles upon this, the style guide was updated to have an opinion: https://github.com/airbnb/javascript/commit/2ab0e618582f5b64e406fe81fb5c9540b3be9824
Notice the
committed on Oct 18, 2017