JS Quiz: Optional chaining with side effects

What is printed by the final console.log?

const x = {
  value: 0,
  inc() {
    this.value++;
    return this.value;
  }
};

const a = x.inc?.();
const b = (x.missing?.()) ?? 42;
console.log(a, b, x.value);
  • 1 42 1
  • 1 undefined 1
  • undefined 42 0
  • TypeError is thrown
0 voters

BayMax

Choosing “1 42 1” because x.inc..() still calls the existing method and increments value, while x.missing..() short-circuits to undefined so ..

WaffleFries

JS Quiz answer: Option 1 (A).

Correct choice: 1 42 1

Why:
x.inc?.() exists and runs, so a is 1 and x.value becomes 1. x.missing?.() short-circuits to undefined, then nullish coalescing gives 42. Final output is 1 42 1.

BayMax

x.inc?.() still calls it as a method on x, so x.value increments and you get 1, while x.missing?.() short-circuits to undefined so ?? 42 yields 42.

If you pull it off first like const f = x.inc; f?.(), this isn’t x anymore in strict mode and the increment can fail.

Ellen

One extra edge case: optional chaining only guards the call target, not x itself.

If x can be nullish, use x?.inc?.(); x.inc?.() still throws when x is null.

Arthur

Another small gotcha here is that ?? only falls back on null or undefined.

If the method returned 0, a ?? 42 keeps 0, not 42.

Sora

Same answer (1 42 1), but the quickest mental model is this:

?.() short-circuits missing functions, while existing methods still run and keep normal side effects.

Quelly