← Back to JavaScript, page 4

javascript-0068 · Easy fresher

How does short-circuit evaluation work, and what are the logical assignment operators ||=, &&=, and ??=?

The operators &&, ||, and ?? evaluate the right side only when the left side does not already decide the result, and they return one of their operands. The logical assignment operators ||=, &&=, and ??= assign only under the matching condition: when the left is falsy, truthy, or nullish. They are shorter than writing the if statement and also skip the assignment when it is not needed.

Full answer

Short-circuit evaluation means the engine stops as soon as the result is known. For a && b, if a is falsy the answer is a and b is never evaluated. For a || b, if a is truthy the answer is a. For a ?? b, if a is anything except null and undefined, the answer is a. The skipped side may be a function call, so side effects do not happen. This makes patterns like isReady && start() or cache[key] || compute(key) possible, although an if statement is usually clearer for side effects.

The three logical assignment operators combine this with assignment:

  • a ||= b means a || (a = b). It assigns only if a is falsy.
  • a &&= b means a && (a = b). It assigns only if a is truthy.
  • a ??= b means a ?? (a = b). It assigns only if a is null or undefined.

??= is the most useful. It sets a default without overwriting 0, false, or an empty string, for example options.retries ??= 3. ||= replaces any falsy value, which is rarely wanted for numbers. &&= updates a value only if it exists.

Unlike a = a || b, the logical forms do not perform the assignment when the condition fails. This matters for setters and for frozen or read-only properties, because no write is attempted. The ternary condition ? x : y is the choice when both outcomes are values, and it should not be nested deeply.

javascript
const calls = [];
const tracked = (label, value) => {
  calls.push(label);
  return value;
};

console.log(tracked('left', 0) && tracked('right', 'x'), calls);
calls.length = 0;
console.log(tracked('left', 'a') || tracked('right', 'b'), calls);
calls.length = 0;
console.log(tracked('left', null) ?? tracked('right', 'fallback'), calls);

const options = { retries: 0, label: '', timeout: undefined, verbose: true };
options.retries ||= 3;
options.label ||= 'untitled';
options.timeout ??= 5000;
options.verbose &&= 'yes';
options.missing &&= 'never set';
console.log(options);

const settings = { retries: 0, name: '' };
settings.retries ??= 3;
settings.name ??= 'guest';
console.log(settings);

const locked = Object.freeze({ mode: 'dark' });
locked.mode ||= 'light'; // condition is truthy, so no write is attempted
console.log(locked.mode);
try {
  (function () {
    'use strict';
    locked.mode = locked.mode || 'light'; // always writes, so strict mode throws
  })();
} catch (error) {
  console.log('plain assignment on frozen object:', error.name);
}

const score = 72;
const grade = score >= 90 ? 'A' : score >= 60 ? 'B' : 'C';
console.log(grade);

Run with Node.js v24.22.1 as js-68.js; two runs gave identical output. Output: 0 [ 'left' ] a [ 'left' ] fallback [ 'left', 'right' ] { retries: 3, label: 'untitled', timeout: 5000, verbose: 'yes' } { retries: 0, name: '' } dark plain assignment on frozen object: TypeError B

Key points

  • Short-circuit operators skip the right side when the left side decides the result.
  • They return an operand, not necessarily a boolean.
  • ||= assigns on falsy, &&= on truthy, ??= on null or undefined.
  • ??= is the safe way to set defaults for values like 0 and false.
  • The logical forms skip the write when the condition fails.

Common mistakes

  • Using ||= for numeric defaults and replacing a valid 0.
  • Relying on short-circuit expressions for important side effects instead of an if statement.
  • Nesting ternary operators until the result is hard to read.
  • Assuming a ||= b always writes; it only writes when a is falsy.

Follow-ups

  • What does a ||= b do for a getter and setter pair?
  • How do short-circuit operators interact with optional chaining?
  • Why is a && b || c not the same as a ternary?

Tips

  • Give the long form for each operator, such as a ?? (a = b); it proves you know what they do.
  • Recommend ??= for defaults and explain the zero example.
  • Keep side effects in if statements and say so.