Operators & Short-Circuit Evaluation

Difficulty: Beginner

Question

Explain short-circuit evaluation in JavaScript. How do &&, ||, and ?? differ?

Answer

Short-circuit evaluation means JavaScript stops evaluating a logical expression as soon as the result is determined. With &&, if the left side is falsy, it returns immediately without evaluating the right side. With ||, if the left side is truthy, it returns immediately.

The || operator returns the first truthy value or the last value. It treats all falsy values the same: 0, '', null, undefined, NaN, false. The ?? (nullish coalescing) operator was introduced to solve this - it only short-circuits on null or undefined, not on other falsy values like 0 or ''.

Optional chaining (?.) is related - it short-circuits property access when the left side is null or undefined, returning undefined instead of throwing a TypeError.

Code examples

Short-Circuit with && and ||

// || returns first truthy value (or last value)
console.log(null || 'default');    // 'default'
console.log('hello' || 'default'); // 'hello'
console.log(0 || 42);              // 42
console.log('' || 'fallback');     // 'fallback'

// && returns first falsy value (or last value)
console.log('hello' && 'world');   // 'world'
console.log(null && 'world');      // null
console.log(1 && 2 && 3);          // 3
console.log(1 && 0 && 3);          // 0

|| finds the first truthy operand, && finds the first falsy operand. Neither returns true/false - they return the actual operand value.

Nullish Coalescing (??) vs OR (||)

// Problem with || for default values
const port = 0;
console.log(port || 3000);  // 3000 (wrong! 0 is valid)
console.log(port ?? 3000);  // 0    (correct!)

const name = '';
console.log(name || 'Anonymous');  // 'Anonymous' (wrong if '' is valid)
console.log(name ?? 'Anonymous');  // ''           (correct!)

const value = null;
console.log(value ?? 'default');   // 'default'
const value2 = undefined;
console.log(value2 ?? 'default');  // 'default'

?? only treats null and undefined as 'missing'. || treats all falsy values (0, '', false, NaN) as 'missing'. Use ?? when 0 or '' are valid values.

Optional Chaining (?.)

const user = {
  name: 'Alice',
  address: {
    city: 'Mumbai'
  }
};

console.log(user.address?.city);     // 'Mumbai'
console.log(user.phone?.number);     // undefined (no error)
console.log(user.getAge?.());        // undefined (no error)

// Combining with ??
const city = user.address?.zipCode ?? 'Not provided';
console.log(city);

// Array access
const arr = [1, 2, 3];
console.log(arr?.[0]);   // 1
console.log(null?.[0]);  // undefined

Optional chaining returns undefined instead of throwing when accessing properties on null/undefined. It pairs perfectly with ?? for default values.

Key points

Concepts covered

Logical Operators, Short-Circuit, Nullish Coalescing, Optional Chaining, Ternary