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:

  1. if (someVeryLongCondition())
  2. doSomething();
  3. 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.

  1. 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:

  1. class InnerClass {
  2. constructor() {}
  3. /** @param {number} foo */
  4. method(foo) {
  5. if (condition(foo)) {
  6. try {
  7. // Note: this might fail.
  8. something();
  9. } catch (err) {
  10. recover();
  11. }
  12. }
  13. }
  14. }

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:

  1. function doNothing() {}

Disallowed:

  1. if (condition) {
  2. // …
  3. } else if (otherCondition) {} else {
  4. // …
  5. }
  6. try {
  7. // …
  8. } catch (e) {}