JS Quiz: Medium: 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

Quelly

1 42 1.

x.inc?.() is still a normal method call when inc exists, so this is x and the side effect happens (value goes 0 → 1, and a is 1). x.missing?.() short-circuits to undefined, so the ?? 42 kicks in and b becomes 42.

Where people get burned is when you detach it first: const f = x.inc; f?.() loses the receiver, so this isn’t x anymore.