Skip to content

Logical Short Circuiting

The logical operators work out their operands from left to right and stop as soon as the result is known. This is short-circuiting, and it means the right-hand operand may never run:

  • a && b stops at a if a is falsy, because the result is then falsy whatever b is.
  • a || b stops at a if a is truthy, because the result is then truthy whatever b is.
  • a ?? b stops at a if a is anything other than null or undefined.

The check function below logs its name whenever it runs, which shows which operands are worked out:

const check = (name, result) => {
console.log(`checked ${name}`);
return result;
};
console.log(check('A', false) && check('B', true));
console.log('---');
console.log(check('C', true) || check('D', true));
console.log('---');
console.log(check('E', true) && check('F', true));

This prints:

checked A
false
---
checked C
true
---
checked E
checked F
true

B and D are never called. Only in the last case, where the left operand does not settle the answer, does the right one run.

Because && stops at a falsy value, it can guard an expression that would fail on a missing value:

const users = [{ name: 'Ana', email: 'ana@example.com' }, { name: 'Ben' }];
for (const user of users) {
const domain = user.email && user.email.split('@')[1];
console.log(user.name, domain);
}

This prints:

Ana example.com
Ben undefined

For Ben, user.email is undefined, so split is never called and the expression gives undefined instead of throwing a TypeError. Optional chaining does the same job more directly, as user.email?.split('@')[1].

condition && action() runs the action only when the condition is truthy:

const log = [];
const debug = false;
debug && log.push('starting');
log.push('done');
console.log(log);

This prints:

[ 'done' ]

The pattern is common in older code and in minified code. In code written for people to read, if (debug) log.push('starting'); says the same thing more plainly.

Three assignment operators combine an operator with =, and short-circuit in the same way, so the assignment happens only when it is needed:

  • a ||= b assigns b only if a is falsy.
  • a &&= b assigns b only if a is truthy.
  • a ??= b assigns b only if a is null or undefined.
const order = { items: 3, note: '', discount: 0 };
order.note ||= 'No note';
order.discount ??= 10;
order.items &&= order.items + 1;
console.log(order);

This prints:

{ items: 4, note: 'No note', discount: 0 }

The empty note was falsy, so ||= replaced it. The discount of 0 is not null or undefined, so ??= left it alone.

Steve Griffith covers this topic in his video Logical Short-Circuiting in JavaScript.