Destructuring — unpacking arrays and objects, with defaults that fire only on undefined¶
Level: 101 · for anyone unpacking function results and options objects
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: A destructuring default fires only for undefined: const { a = 1 } = { a: null } leaves a as null and const [c = 1] = [0] keeps 0; and destructuring null itself throws a TypeError, even when the pattern asks for nothing.
Keywords: destructuring, destructuring assignment
What the finished page will answer¶
- Which values trigger a destructuring default (
undefined,null,0, a missing index), and is the default evaluated when it is not needed? - What error does destructuring
nullgive with an object pattern, and what doesconst [z] = undefinedgive? - Why does
{ a } = obj;on its own line fail to parse, and what do the parentheses in({ a } = obj);fix? - What does
const [first] = "\u{1F600}x"put infirst, compared with"\u{1F600}x"[0]? - How do renaming (
{ a: alias }), a nested default and...restcombine in one pattern?
Examples it will need¶
-
destructuring_defaults_js.js— defaults tried against undefined, null, 0, an empty string and a missing index, with the value bound each time -
destructuring_errors_js.js— the TypeErrors from destructuring null and undefined with object and array patterns -
destructuring_patterns_js.js— renaming, nesting, rest, and a string destructured by code point
See also¶
- Parameters — parameter defaults follow the same
undefinedrule - Copying objects — rest in a pattern makes a shallow copy
nullandundefined— the one value that triggers a default- The iteration protocol — an array pattern pulls its values from an iterator
- Automatic semicolon insertion — the swap that a missing semicolon breaks
- Rust: Destructuring structs ↗ — struct patterns in Rust name the fields you want
- Rust: Irrefutable patterns ↗ — which patterns a Rust
letaccepts, and why - Rust:
let else↗ — a pattern that may fail, with anelseto handle it