Destructuring objects

Destructuring allows you to bind a set of variables to a corresponding set of values anywhere that you can normally bind a value to a single variable.

It helps pull incoming objects apart.

Irrefutable pattern

The destructuring must match the object or else it will throw an error.

var person = {name: 'Aaron', age: 35};
let {name, age, address} = person; // throws! (irrefutable)
let {name, age, ?address} = person; // is ok because we specified address as undefineable (refutable)
let ?{name, age, address} = person; // Forgives the whole pattern

All patterns

let {a: x} = {}   // throw
let ?{a: x} = {}  // x = undefined
let ?{a: x} = 0   // x = undefined
let {?a: x} = {}  // x = undefined
let {?a: x} = 0   // throw

Patterns w/ Default Values

let ?{a: x = 1} = undefined   // x = 1
let {?a: x = 1} = undefined   // throw
let {?a: x = 1} = {}          // x = 1

Patterns - Nested

let person = {
  name: 'Aaron',
  age: '35',
  address: {
    city: 'Salt Lake City',
    state: 'UT',
    zip: 84115,
  },
};

let {
  name,
  age,
  address: { city, state, zip },
} = person; // this won't create address, but will create city, state, zip

results matching ""

    No results matching ""