Search⌘ K
AI Features

Destructuring

Explore the destructuring assignment in JavaScript as a shorthand to extract data from arrays and objects. Understand its syntax, use cases like variable swapping, default values, and parameter unpacking to write cleaner, more efficient code.

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 lesson, we go through the syntax of both data structures and give examples of when you can use them.

Destructuring arrays

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

var fruit = ['apple', 'banana', 'kiwi'];

var apple = fruit[0];
var banana = fruit[1];
var kiwi = fruit[2];

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 ...