4.1 Braces
4.1.1 Braces are used for all control structures
Braces are required for all control structures (i.e. if
, else
, for
, do
,while
, as well as any others), even if the body contains only a singlestatement. The first statement of a non-empty block must begin on its own line.
Disallowed:
if (someVeryLongCondition())
doSomething();
for (let i = 0; i < foo.length; i++) bar(foo[i]);
Exception: A simple if statement that can fit entirely on a single line withno wrapping (and that doesn’t have an else) may be kept on a single line with nobraces when it improves readability. This is the only case in which a controlstructure may omit braces and newlines.
if (shortCondition()) foo();
4.1.2 Nonempty blocks: K&R style
Braces follow the Kernighan and Ritchie style (Egyptian brackets
) fornonempty blocks and block-like constructs:
- No line break before the opening brace.
- Line break after the opening brace.
- Line break before the closing brace.
- Line break after the closing brace if that brace terminates a statement orthe body of a function or class statement, or a class method. Specifically,there is no line break after the brace if it is followed by
else
,catch
,while
, or a comma, semicolon, or right-parenthesis.
Example:
class InnerClass {
constructor() {}
/** @param {number} foo */
method(foo) {
if (condition(foo)) {
try {
// Note: this might fail.
something();
} catch (err) {
recover();
}
}
}
}
4.1.3 Empty blocks: may be concise
An empty block or block-like construct may be closed immediately after it isopened, with no characters, space, or line break in between (i.e. {}
),unless it is a part of a multi-block statement (one that directly containsmultiple blocks: if
/else
or try
/catch
/finally
).
Example:
function doNothing() {}
Disallowed:
if (condition) {
// …
} else if (otherCondition) {} else {
// …
}
try {
// …
} catch (e) {}