QuestionsJavaScript

Destructuring, defaults, and rest/spread in depth

DestructuringMediumJavaScript

Show non-trivial destructuring: renaming, nested, defaults, rest, and swapping — and where defaults actually fire.

What it tests

Fluency with the assignment-target grammar, and knowing defaults trigger only on undefined (not null).

Approach & answer

Destructuring unpacks arrays by position and objects by key into bindings. Object destructuring can rename (`{ a: x }` binds x), reach into nested shapes (`{ user: { name } }`), and supply defaults (`{ page = 1 }`). Array destructuring binds by index, can SKIP holes (`[, , third]`), and collects the tail with a rest element (`[first, ...rest]`). The rest pattern also works on objects (`{ id, ...others }`) — a clean way to omit a key while keeping the remainder (great for React prop forwarding). Two precise rules interviewers probe: (1) a default value fires ONLY when the source value is `undefined`, never when it is `null` — `const { x = 5 } = { x: null }` yields null, not 5. (2) Defaults are evaluated lazily and can reference earlier bindings (`{ a, b = a * 2 }`). Combined with default parameters you get self-documenting function signatures: `function f({ retries = 3, signal } = {})` — the `= {}` guard lets you call f() with no argument at all. Swapping without a temp is the one-liner `[a, b] = [b, a]`. Watch the gotcha: a statement STARTING with `{` is parsed as a block, so wrap standalone object-destructuring assignments in parens: `({ a } = obj)`.

Use this technique when

Cleanly pulling fields from props/options objects, forwarding 'the rest' of props, and writing ergonomic optional-config function signatures.

References

js