Skip to main content
CodeOath
← All posts

JavaScript60 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Part 10 of 16 · ~2 min

Optional Chaining and Nullish Coalescing

Not every candidate record is at the same stage. Lena was rejected before an interview was ever scheduled, so she has no feedback object at all:

const interviewer = candidates[4].feedback?.interviewer?.name; // undefined — no throw, Lena has no feedback yet
const shownScore = candidates[4].score ?? "not yet scored";     // 59 — she does have a score, so it's kept

The moment ?. runs into a null or undefined, it abandons the rest of the whole chain right there, not just the one property access sitting next to it:

candidates[4].feedback.interviewer; // TypeError — feedback is undefined, and this tries to read .interviewer off it

candidates[4].feedback?.interviewer.name;
// undefined — feedback is undefined, so the chain stops right there and never even
// attempts to read .name, which means it can't throw on interviewer being missing either

The same guard extends to calling a method that isn't guaranteed to be there, and to reading an index off something that might not even be an array:

candidates[4].cancelInterview?.();  // calls it only if it exists on this record, otherwise evaluates to undefined
searchResults?.[0];                  // safe first-element access even if searchResults itself is null

?? is deliberately narrower than ||, and the difference matters most exactly where a "falsy" value is still a real, meaningful one:

const displayed = candidates[4].score || "N/A"; // WRONG — a real score of 0 would show "N/A" instead
const displayedFixed = candidates[4].score ?? "N/A"; // correct — only null/undefined fall back

console.log(candidates[4].score);      // 59 — not falsy, both versions happen to agree here
console.log(0 || "N/A");               // "N/A" — but if the score WERE 0, this would be wrong
console.log(0 ?? "N/A");               // 0 — correct, a real score of zero is kept

A candidate who genuinely scored 0 on a screening round is different from a candidate who hasn't been scored yet at all, and || can't tell those two cases apart — 0, "", and false are all falsy, but none of them mean "missing." ?? only falls back on null or undefined specifically, which is what "missing" actually means.