liveBook · Manning

Destructuring assignment

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A JavaScript assignment form that extracts properties from an object into distinct variables, optionally renaming the bindings.

Need several values from an object or array? Destructuring assignment pulls them out in one statement instead of repeating property or index lookups. Object patterns select by property name; array patterns select by position. section 11.0 section 11.5

Pick properties—and choose binding names

Given `let person = { name: 'Christina', age: 25 };`, `let { name, age } = person;` creates `name` and `age` with those values. To choose different variable names, write `let { name: firstName, age: yearsOld } = person;`. The names before the colons identify properties; the names after them are the bindings you create. section 11.1

Follow a nested pattern to its leaves

Given `let result = { coords: [51.0, -0.1] };`, write `let { coords: [latitude, longitude] } = result;`. First, `coords` selects the property. Then `[latitude, longitude]` takes its first and second array values. Only the leaves become variables: this statement does not create a `coords` binding. The same rule applies to nested object patterns. section 11.3 section 11.1

A few useful distinctions:

  • `let [lat, lng] = [51.0, -0.1];` follows positions, not names. Swap existing variables without a temporary one using `[start, stop] = [stop, start];`. section 11.2
  • Object destructuring can read indexed properties from an array, but their numeric keys need renamed bindings: `const { 0: first, length } = ['foo', 'bar'];`. Array-style destructuring also works with iterables such as strings and Sets; the iterable protocol is treated separately. section 11.4

Unpack a function argument

If `visualize` receives an array of three results, `function visualize([inserted, deleted, modified]) { /* ... */ }` extracts them in the parameter list. If it receives an object instead, use `{ inserted, deleted, modified }`: object property order need not match, but the property names must. For optional object settings, `function car({ make = 'Ford', year = 2017 } = {}) { /* ... */ }` gives each omitted property a fallback and permits `car()` as well as `car({ year: 1965 })`. section 16.1 section 16.2 section 16.3

Property names need not be consistent across callers: `function setCoordinates({ lat, lon, lng = lon }) { /* use lat and lng */ }` accepts either `lon` or `lng`, using `lon` when `lng` is absent. A Map is different from an ordinary options object: it cannot be destructured by its key names this way. Array-style destructuring reads its entries by position instead. section 16.4 section 25.3

Try replacing repeated reads such as `product.details.price` and `product.images.others[0]` with one nested pattern. Check which parts select a path and which parts actually create bindings. section 11.3 section 11.5

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Works through property names, array positions, renaming, nesting, parameter defaults, and destructurable types; defers the iterable protocol.
Examples
Uses coordinates, product data, swapped variables, visualization inputs, and optional car settings to demonstrate patterns.
What it assumes
Assumes familiarity with objects, arrays, variables, and functions while introducing destructuring syntax through short examples.
What you can do after
Practice/perform nested extraction, binding renames, variable swaps, and parameter unpacking with optional defaults.
How it connects
Connects object and array literals, function parameters, default values, iterables, and Maps to different ways of unpacking values.

Also explained in

Compare how 6 books explain destructuring assignment →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.