Stanza

braces

The braces around a single statement control flow body, and the cases that keep them.

A control flow body that is a single statement has no braces.

function retry(task: Task, attempts: number) {
  if (attempts === 0) {
    throw new Error(`${task.name} failed`);
  }
  if (attempts === 0) throw new Error(`${task.name} failed`);

  while (!task.done) {
    task.run();
  }
  while (!task.done) task.run();

  for (const listener of task.listeners) {
    listener.notify(task);
    listener.close();
  }
}

Applies to the block owned by an if (the consequent or the else) and by any loop, at any depth, module top level included. When the block holds exactly one statement of a removable kind (an expression, return, throw, break, continue, a nested if or a loop), the braces go. A body that fits goes up onto its header line, if (done) return;, the way your formatter would print it, so the formatter has nothing left to join. It fits when the header, one space and the body make a line no wider than the formatter width. A body that does not fit, a header that spans lines, or a line comment before the brace keeps the body on its own line. Stanza never reflows the code inside the body. do { tick(); } while (busy) loses its braces too. In the example the for keeps its braces because its block holds two statements. Braces That Stay lists every case.

A statement under stanza-ignore keeps its own braces, else if chain and label included, while the code nested inside it is still formatted (see Directives). --no-braces turns the rule off, and so does a lint config that enforces braces. Braces and Lint Config covers both.

Removing braces changes which statements are compact, so the blank line rules see the unbraced code. Compact means on one line, or a braceless if, for or while whose joined line fits the formatter width. An if with else is compact when every arm is braceless and fits on its own line, else included, as if (ready) send(); over else close();. When unbracing leaves a body of 2 or 3 compact statements, short-body removes the blank lines between them. A body too long to join stays on its own line, the formatter keeps it there, and the statement counts as multi-line.

Braces That Stay

The else branch loses its braces. The outer if keeps them because its body ends in an if without else, and the while keeps them because of the comment.

function pick(items: Item[], strict: boolean) {
  if (items.length > 1) {
    if (strict) log("many");
  } else {
    log("one");
  }
  } else log("one");

  while (items.length > 0) {
    // drop the last one
    items.pop();
  }
}

On this page