Search⌘ K
AI Features

Array & Object Destructuring

Explore array and object destructuring techniques in JavaScript to simplify extracting values, assign variables with defaults, and streamline function parameters. Understand how these ES2015+ features enable cleaner and more readable code, including usage with arrow functions.

We'll cover the following...

Array and object destructuring can truly change the way we write a lot of our code. Let’s dive right in and explain by example.

Before, to get values out of an array or object, we’d have to use direct assignment.

Javascript (babel-node)
var arr = [1, 2, 3];
var one = arr[0];
var two = arr[1];
var three = arr[2];
console.log(one, two, three); // -> 1 2 3
// ---------------------------------------
var obj = {
key1: 'val1',
key2: 'val2'
};
var key1 = obj.key1;
var key2 = obj.key2;
console.log(key1, key2); // -> val1 val2

Now we have a new tool.

Javascript (babel-node)
const arr = [1, 2, 3];
const [one, two, three] = arr;
console.log(one, two, three); // -> 1 2 3
// ---------------------------------------
const obj = {
key1: 'val1',
key2: 'val2'
};
const { key1, key2 } = obj;
console.log(key1, key2); // -> val1 val2

We’ve just witnessed a new way to assign values to variables. It’s as simple as following the pattern shown. It’s called destructuring and can be thought of as breaking down the object/array into its individual components.

Line 2 above pulls the numbers 1, 2, and 3 out of the array and gives them to the variables one, two, and three, respectively. Any variable names can be used. These are constant variables, as we used the keyword const in ...