Destructuring Assignment In JavaScript

“Destructuring assignment” isn’t the friendliest name. I think that’s because it’s an unfamiliar concept. Look at just these few examples and I think you’ll be able to get your head around it.

Consider a JS array or an object:

let myArray = [
  'Maya',
  'Ray'
];

let myObject = {
  firstName: 'Tony',
  lastName: 'Baloney'
};

Each of these is more complex than a single value, like 5 or 'foo'. Each has a structure: The array is an ordered list of stuff. The object is basically a collection of key/value pairs.

When you do a destructuring assignment, what you’re doing is reaching into the structure of an array or an object to get at something inside it, and assigning that something to a variable outside.

With an array, it looks like this:

let myArray = [
  'Maya',
  'Ray'
];

let [one, two] = myArray;

console.log(one); // prints 'Maya'
console.log(two); // prints 'Ray'

With an object:

let myObject = {
  firstName: 'Tony',
  lastName: 'Baloney'
};

let { firstName: first, lastName: last } = myObject;

console.log(first); // prints 'Tony'
console.log(last); // prints 'Baloney'

In both cases, you provide some structure on the left side of the assignment statement. This information is needed for JS to know how to map stuff from inside the array or object onto your new variables.

There are lots of small notes about the ins and outs of destructuring assignment. I’m tempted to add them, but my goal here is to introduce the concept and basic syntax, not to provide documentation.

Okay, one small note: With an array destructuring assignment, you can use the spread operator!

let beatles = [
  'John',
  'Paul',
  'George',
  'Ringo'
];

let [first, second, ...rest] = beatles;

console.log(first); // prints 'John'
console.log(second); // prints 'Paul'
console.log(rest); // prints 'George,Ringo'

Apologies to George and Ringo.