Sign up for Digital Ocean VPS and get $10 credit FREE!

ES6/ES2015 For Newbies Lesson 5: Destructuring2 min read

Source Code

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

Say I have an array:

const list = ['a', 'b', 'c', 'd'];

If I want to set each item in the array to a set of variables, I would have to do this:

var first = list[0];
var second = list[1];
var third = list[2];

this is both ugly and tedious to type.  Here’s how you can do it with destructuring assignment:

const [first, second, third] = list;

that’s it!  It sets the variable first to the corresponding element from the list array, which is asecond to the second element from list array and so on.

With default values

You can also set default values when destructuring:

// With default values
[first, last, age, gender='male'] = ['penta', 'code', 5];
console.log(first, last, age, gender);

Here, gender does not have a corresponding element from the array on the right, so it sets its value to the default value provided: male.

 With Spread

// Use with Spread
var [a, b, ...c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c);

Spread works flawlessly with destructuring, C will be set to equal to [4, 5, 6].

Swap two values

let a = 10, b = 20;
[b, a] = [a, b];
console.log(a, b);

You can accomplish swapping of values easily without the need for a third variable.

Destructure with Objects

// Destructuring with Objects
let {name: name} = {name: 'bob'};
//short hand: let {name} = {name: 'bob'};
console.log(name);

You can destructure objects too by providing a corresponding key with the corresponding object’s key, so when you do

let {name: name} = {name: 'bob'};

You are saying to let the variable name to be the value of the property name from the {name: ‘bob’} object.  There’s also a short hand way of writing it, if you remember our previous lesson on enhanced object literals, {name: name} can be rewritten to {name}

pretty neat right?

I’ll leave you with a real world example where you can use destructuring to make your code much more easier to read:

const someFunction = ({
	url: url = '/api/endpoint',
	method: method = 'GET'},
	...rest
) => {
	console.log(`url: ${url}   Method: ${method}    Rest: ${rest}`);
};

someFunction({url: 'www.test.com/api', method: 'POST'}, 'name', 'age', 'location');

[frames playlist=’3′]

 

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

Related Posts

Webdev News

Loading...
    More News