Technical skill practice
JavaScript OR Operator: Returned Operands and Short-Circuit Calls
The || operator returns its first truthy operand, or the final operand when earlier ones are falsy. It can skip evaluating the right-hand expression. Use a trace to see which calls actually run.
The task
Choose a display label from a supplied value or a fallback function. Compare an existing label, an empty string and a zero value while recording fallback calls.
Runnable Node 22 example
const assert = require('node:assert/strict');
const calls = [];
function fallback() { calls.push('fallback'); return 'unassigned'; }
const present = 'desk-4' || fallback();
assert.equal(present, 'desk-4');
assert.deepEqual(calls, []);
const blank = '' || fallback();
assert.equal(blank, 'unassigned');
assert.deepEqual(calls, ['fallback']);
assert.equal(0 || 9, 9);
assert.equal(0 ?? 9, 0);
assert.equal(false || 'next', 'next');
console.log(`present=${present}; blank=${blank}; calls=${calls.length}`);
Expected output and explanation
The first nonempty label ends the evaluation before fallback runs. The empty string reaches the function, which returns unassigned and records one call. The operator result is that string, not the Boolean true.
Zero also triggers || in the numeric comparison, while ?? preserves it. That short contrast identifies the boundary; the dedicated nullish-coalescing guide supplies the complete fallback exercise. Pick the operator according to whether your application means “falsy” or specifically “nullish.”
Output from the example
present=desk-4; blank=unassigned; calls=1
Pitfall to check
Put required side effects outside an expression that may short-circuit. If a function must run for logging or validation, hiding it on the right of || can skip it for valid-looking input. Explicit control flow can make those requirements clearer.
Questions, answered
Does || convert its final result to true or false?
No. Its conditional decision uses truthiness, but it returns a selected operand. Apply an explicit Boolean conversion only when a Boolean result is actually needed.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.