Glossary / Ternary expressions

Ternary expressions

The conditional (ternary) operator has the form condition ? consequent : alternate. It evaluates the condition for truthiness, evaluates exactly one branch, and returns that branch’s value. Because it is an expression, it can appear where a value is expected, such as an assignment or return statement.

Behavior and readability

function statusLabel(isOnline) {
  return isOnline ? "Online" : "Offline";
}

The condition need not be a Boolean; JavaScript applies truthiness. If the desired rule is more specific, make it explicit (value !== null, for example). Nested ternaries associate to the right and can be difficult to scan:

const label = loading ? "Loading" : error ? "Error" : "Ready";

For several branches, side effects, or complex conditions, if/else or a switch is often clearer. Do not use a ternary only to save lines. Both branches are expressions; code with block statements belongs in an if statement or an immediately invoked function, not directly in a ternary branch.

Interview questions

  1. Are both branches evaluated? No, only the selected branch is evaluated.
  2. Must the condition be Boolean? No; it is interpreted by truthiness.
  3. When prefer if/else? Complex/nested conditions, multiple statements, or side-effectful control flow.
  4. What does the ternary return? The value of the selected consequent or alternate expression.

References