Getting Started with Modern JavaScript — Destructuring

Michael Karén
3 min readSep 3, 2020

The two most used data structures in JavaScript are Object and Array. The destructuring assignment introduced in ECMAScript 2015 is a shorthand syntax that allows us to extract array values or object properties into variables. In this article, we go through the syntax of both data structures and give examples when you can use them.

Destructuring Arrays

In ES5 you could access items in an array by index:

With ES6 destructuring, the code becomes simpler:

const [apple, banana, kiwi] = fruit;

Sometimes you might want to skip over items in the array being destructured:

const [,,kiwi] = ['apple', 'banana', 'kiwi'];

Or you can save the other items in an array with the rest pattern:

const [apple, …rest] = ['apple', 'banana', 'kiwi'];console.log(rest); // -> ['banana', 'kiwi']

Note that the destructuring assignment pattern works for any iterable.

Destructuring Objects

Object destructuring lets you extract properties from objects and bind them to variables. Instead of accessing width through rectangle.width we can access the property and assign it to a variable:

const rectangle = { width: 5, height: 8 };const { width } = rectangle;

What’s even better, object destructuring can extract multiple properties in one statement. This makes the code clearer. The order of the properties does not matter.

const { width, height } = rectangle;

If we want to change the name of the property we can do it using a colon:

const { width: w, height: h } = rectangle;console.log(w); // -> 5

Here we assign the property width from rectangle to a variable named w.

--

--

Michael Karén

Frontend Architect • JavaScript Enthusiast • Educative.io Author • ngVikings organizer.