Destructuring
This lesson will introduce you to the syntax of destructuring in JavaScript and the various ways we can use it in our 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 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;
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 width
property from rectangle
to a variable named w
.
Default values
When you destructure on properties that are not defined, you get undefined
:
const { password } = {};
console.log(password); // -> undefined
You can provide default values for when the property you are destructuring is not defined:
const [favorite = 'apple'] = [];
console.log(favorite); // -> apple
const { width = 100 } = {};
console.log(width); // -> 100
Examples
There are many places where we can use destructuring to make the code terser. Let’s see some examples!
String manipulation
We could, for example, do some string manipulation on a name and directly assign the firstName
and lastName
variables to it:
const [firstName, lastName] = 'Max Best'.split(' ');
// firstName = 'Max', lastName = 'Best'
Swapping variable values
Let’s first do the ES5 swap:
var me = 'happy', you = 'sad';
var temp = me;
me = you;
you = temp;
// me = 'sad', you = 'happy'
Now, let’s swap back to ES6 destructuring:
[me, you] = [you, me];
// me = 'happy', you = 'sad'
No more temporary variables needed!
Get hands-on with 1400+ tech skills courses.