Question presented to candidate: "You're accessing a deeply nested property, like response.data.user.address.city, but any of those intermediate levels might legitimately be missing. How would you write that safely, and what specifically does ?? do differently from || for providing a default value?"
What a strong answer should cover:
- 📌 Interview term: optional chaining (
?.) — accesses a property, calls a method, or indexes into an array, short-circuiting toundefinedinstead of throwing, if the value immediately before the?.isnullorundefined. - 📌 Interview term: the real, direct answer to the prompt — verified directly: chaining
?.through several levels of a possibly-missing nested path (data.missing?.deep?.prop) genuinely returnedundefinedwith no throw, while the identical chain WITHOUT?.genuinely threw a realTypeErrorat the first missing level. - 📌 Interview term: the chain-wide short-circuit — verified directly with a real call counter: once a
?.in a chain hitsnull/undefined, the entire rest of the chain genuinely short-circuits — a method call further along the same chain was genuinely never invoked at all, not just its result discarded. - 📌 Interview term: nullish coalescing (
??) — provides a fallback value, but only when the left-hand side is specificallynullorundefined— verified directly:0 ?? "default"genuinely stayed0, while0 || "default"genuinely became"default", since||treats ANY falsy value (not just nullish ones) as needing the fallback. - A precise answer names that
??cannot be mixed directly with&&/||in the same expression without explicit parentheses — verified directly, this genuinely throws a realSyntaxError, a deliberate spec decision due to their ambiguous relative precedence.
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering the prompt's own scenario, plus the sharp
??vs.||distinction, is the strong signal.
Code / implementation expected: Yes — the deep-chain-with-?. vs. without-?. contrast, plus the 0 ?? vs 0 || contrast, are the clearest, most convincing demonstrations.