Question presented to candidate: "You need to swap the values of two variables, and separately, pull a deeply nested value plus a couple of top-level ones out of a config object, giving one of them a different local name and a fallback if it's missing. Walk me through how destructuring handles both, and what happens if you try to destructure something like null?"
What a strong answer should cover:
- 📌 Interview term: destructuring — a real, single-expression syntax for unpacking array elements (by position) or object properties (by name) directly into variables, supporting defaults, renaming, skipping, and nested patterns all at once.
- 📌 Verified, not assumed — directly answering the swap sub-question: real array destructuring genuinely swapped two variables' values with no temporary third variable at all —
[x, y] = [y, x]genuinely worked, confirmed by real output. - 📌 Verified, not assumed — directly answering the nested/renamed/default sub-question: a real, single destructuring statement genuinely pulled a renamed top-level property AND a nested property out of a config-shaped object in one expression; a separate, real default-plus-rename combination on a genuinely missing key correctly fell back to the real default value.
- A precise answer names rest in destructuring (
const [head, ...tail] = arr,const { a, ...rest } = obj) as collecting the genuinely remaining elements/properties — a real, distinct but related capability, covered together with spread in this bank's own dedicated question. - 📌 Interview term: destructuring
null/undefinedgenuinely throws — directly answering the prompt's exact question: a real attempt to destructurenullgenuinely threw a real, specificTypeError("Cannot destructure property ... as it is null"), confirmed directly — not a silentundefinedfallback.
Clarifying questions expected:
- "Does the actual source value being destructured ever genuinely come back as null or undefined (from an API response, say), which would need a real guard or default at the OUTER level before destructuring, verified above as otherwise throwing?"
- "Does function-parameter destructuring need its own top-level default (like
function f({...} = {})) for the case where the function is genuinely called with no argument at all?" — a real, common, easy-to-miss requirement verified directly in this answer's own example.
Code / implementation expected: Yes — a real no-temp-variable swap, a real nested-plus-renamed-plus-defaulted object destructure, and a real, direct proof that destructuring null throws a specific error, are the concrete, convincing proof of exactly how the syntax behaves end to end.