Destructuring

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

Object Destructuring

In ECMAScript 5 and earlier, it would take lots of code to extract information from array and objects.

var username = {
    firstName: 'Pandiyan',
    lastName: 'Murugan'
};

var firstName = username.firstName;
var lastName = username.lastName;

console.log(firstName + ' ' + lastName);

Object destructuring syntax uses an object literal on the left side of an assignment operation.

In ECMAScript 6,

var username = {
    firstName: 'MS',
    lastName: 'Dhoni'
};

var {firstName, lastName} = username;

console.log(firstName + ' ' + lastName);

In the above example, username.firstName is stored in firstName and username.lastName is stored in lastName.

var username = {
    firstName: 'MS',
    lastName: 'Dhoni'
};

var { firstName, lastName, designation } = username;

console.log(firstName + ' ' + lastName + ' ' + designation);

// designation will be undefined at this point

We can set default values as follows

var username = {
    firstName: 'MS',
    lastName: 'Dhoni'
};

var { firstName, lastName, designation = 'player' } = username;

console.log(firstName + ' ' + lastName + ' ' + designation);

// designation will be set as player if it didn't find the value for player in username object

Assigning to Different Local Variable Names

In earlier example, we have used same in the local variable with matching name in object. Now lets try to assign it to different variable as follows

var username = {
    firstName: 'MS',
    lastName: 'Dhoni'
};

var {  lastName: localLastName, firstName: localFirstName } = username;

console.log(localFirstName +' '+ localLastName);     // MS Dhoni

Here we can user any order to assign the variables. The values will be properly set.

Array destructuring

Array destructuring syntax is very similar to object destructuring; it just uses array literal syntax instead of object literal syntax.
The destructuring operates on positions within an array, rather than the named properties that are available in objects.

var fruits = [
    'mango',
    'banana',
    'jack fruit'
];

var [fruitOne, fruitTwo, fruitThree] = fruits;

console.log(`${fruitOne} ${fruitTwo} ${fruitThree}`);

Setting default values in array literal is similar to object literals.

Lets cover more ES6 features in upcoming post. Keep reading and supporting.

Happy coding 🙂