Destructuring in ES6

Destructing is used to store the different elements of array and object.

It gives us an very convenient way to extract data from the array or any object.

Now, let us take we have an array filled with some data. And , we want to store each of the elements of the array in a single variable.  In Es5 we have to take separate variables. But in ES6 we can make use of destructing.

<script>

//ES5

var employeeDetails = ["Mohan",25,"Java",true];

//Because we want to store each element of array in separately. So, we have to take separate variables  for each item.

var name = employeeDetails[0];

var age = employeeDetails[1];

var department = employeeDetails[2];

var isMarried = employeeDetails[3];

console.log('The name is '+name);

console.log('The age is '+age);

console.log('The department is '+department);

console.log('Is he married  '+isMarried);

//But suppose we have 20 elements in the array then it will become impractical to store each element separately inside the each variable.

//Now we will use destructing for this.

//ES6

const [name1,age1,department1,isMarried1] = ["Mohan",25,"Java",true];

console.log('The name is '+name1);

console.log('The age is '+age1);

console.log('The department is '+department1);

console.log('Is he married  '+isMarried1);

//So, the above example will create a constant as nam1 and another constant with name age1. So on..

//So, it destruct the data structure

//Example to destruct an object

var obj = {

 firstName : 'Mohan',

 lastName : 'Kumar' 

};

const {firstName,lastName} = obj;

console.log('The first name is '+firstName+" and last name is "+lastName);

//Now, here we do have 2 brand new constants. That store data from the object

//Another way to use it as alias

const {firstName : a,lastName : b} = obj;

console.log(a+"---"+b);

 

The best way to use the destructing is to return multiple values from a function. Generally inside a function , if we want to return multiple values then we will use the object. Or, we will return the object inside the function.

But after intoduction of destructing things became very easy.

function calcAgeRetirement(year){

const age = new Date().getFullYear() - year;

return [age,65-age];

}

const [nage,retirement] = calcAgeRetirement(1986);

console.log('Your age is '+nage+'. You got retire at '+retirement)

 

 

Site Footer