← Back to JavaScript, page 3

javascript-0051 · Easy fresher

What do the optional chaining (?.) and nullish coalescing (??) operators do, and how do they differ from && and ||?

Optional chaining a?.b stops and returns undefined when a is null or undefined, instead of throwing a TypeError. Nullish coalescing a ?? b returns b only when a is null or undefined, so valid values such as 0, false, and an empty string are kept. Together they replace long chains of && and || checks.

Full answer

Reading a property of null or undefined throws a TypeError. Before optional chaining, safe access meant writing user && user.address && user.address.city. The operator ?. does the same in one step: if the value on its left is null or undefined, the whole chain stops and the result is undefined. It works for properties (user?.address), computed keys (list?.[0]), and function calls (callback?.()). The rest of the chain is skipped, so arguments inside the call are not evaluated either.

Optional chaining checks only for null and undefined. A value such as 0 or '' continues the chain normally. It does not hide other errors: calling a property that exists but is not a function still throws.

The operator ?? supplies a default. a ?? b is b only when a is null or undefined. The older a || b returns b for every falsy value, so 0 || 10 gives 10 even when zero was a real answer. Use ?? for defaults when 0, false, or '' are valid data.

The two operators combine well: settings?.volume ?? 50. Mixing ?? with && or || without parentheses is a syntax error, which prevents unclear precedence.

Use optional chaining only where a value may really be missing. Spreading it everywhere hides bugs, because a typo in a property name quietly gives undefined.

javascript
const user = { name: 'Neha', address: null, scores: [0, 45], greet() { return 'hello'; } };

console.log(user.address?.city);
console.log(user.scores?.[0], user.missing?.[0]);
console.log(user.greet?.(), user.shout?.());

let calls = 0;
user.missing?.method(calls++); // arguments are skipped when the chain stops
console.log('argument evaluated:', calls);

try {
  user.address.city;
} catch (error) {
  console.log('without ?.:', error.name);
}
try {
  user.name?.nope(); // name exists, but nope is not a function
} catch (error) {
  console.log('real mistakes still throw:', error.name);
}

const volume = 0;
console.log(volume || 50, volume ?? 50);
const label = '';
console.log(label || 'untitled', label ?? 'untitled');
console.log(user.settings?.theme ?? 'light');

try {
  eval('null || undefined ?? 1');
} catch (error) {
  console.log('mixing without parentheses:', error.name);
}
console.log((null || undefined) ?? 'parenthesized');

Run with Node.js v24.22.1 as js-51.js; two runs gave identical output. Output: undefined 0 undefined hello undefined argument evaluated: 0 without ?.: TypeError real mistakes still throw: TypeError 50 0 untitled light mixing without parentheses: SyntaxError parenthesized

Key points

  • ?. short-circuits to undefined when its left side is null or undefined.
  • It also works for ?.[key] and fn?.() and skips the rest of the chain.
  • ?? falls back only for null and undefined; || falls back for every falsy value.
  • ?? cannot be mixed with && or || without parentheses.
  • Overusing ?. can hide typos and real data problems.

Common mistakes

  • Using || for defaults and replacing valid 0, false, or empty-string values.
  • Believing ?. catches every error. It only guards null and undefined on its left.
  • Putting ?. after every property, which hides typos and missing data bugs.
  • Assigning with the chain on the left side, such as user?.name = 'x', which is a SyntaxError.

Follow-ups

  • What does a?.b.c do when a exists but b is undefined?
  • How does optional chaining behave with delete?
  • What are the logical assignment operators ??=, ||=, and &&=?

Tips

  • Contrast ?? with || using the zero example; interviewers expect that one.
  • Mention that the arguments after a short-circuited call are not evaluated.
  • Say you use ?. only where missing data is expected, not as a habit.