Skip to content

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 null give with an object pattern, and what does const [z] = undefined give?
  • 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 in first, compared with "\u{1F600}x"[0]?
  • How do renaming ({ a: alias }), a nested default and ...rest combine 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

Sources to start from