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 && bstops ataifais falsy, because the result is then falsy whateverbis.a || bstops ataifais truthy, because the result is then truthy whateverbis.a ?? bstops ataifais anything other thannullorundefined.
Seeing it happen
Section titled “Seeing it happen”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 Afalse---checked Ctrue---checked Echecked FtrueB and D are never called. Only in the last case, where the left operand does not settle the answer, does the right one run.
Guarding a property access
Section titled “Guarding a property access”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.comBen undefinedFor 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].
Running code only when a condition holds
Section titled “Running code only when a condition holds”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.
Logical assignment
Section titled “Logical assignment”Three assignment operators combine an operator with =, and short-circuit in the same way, so the assignment happens only when it is needed:
a ||= bassignsbonly ifais falsy.a &&= bassignsbonly ifais truthy.a ??= bassignsbonly ifaisnullorundefined.
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.