Thursday, November 8, 2018

TypeScript - ES6 - arrays and objects destructuring

Consider we have an array of 3 elements. Now, if we want to extract the 3 elements into 3 separate variables simultaneously - then we can use the array destructuring functionality provided by ES6.

Destructuring of Arrays:

const cricketStars = ["Virat Kohli","Ajinkya Rahane","Rohit Sharma"];
let [cricketStar1, cricketStar2, cricketStar3] = cricketStars;
console.log(cricketStar1);
console.log(cricketStar2);
console.log(cricketStar3);

Observe the second line where we are extracting the elements of the array into 3 separate variables. This is destructuring of arrays.

Now, destructuring may also be used for objects.

Destructuring of Objects:
Now, we may apply the same concept to objects in JavaScript. Consider the following Example:

const myCityObj = {myCityName:"Hyderabad",myCityElevation:505}
const {myCityName, myCityElevation} = myCityObj;
console.log(myCityName);
console.log(myCityElevation);

Now, the important thing to note in second line: the name of the variables is the same as the the object keys. This is because in JavaScript Objects - the objects keys are not ordered. Hence, for us to destructure correctly - we need to specify the key names as the variable names to hold the values. In case, we wish to reassign to new variables, we can do it as follows:

const myCityObj = {myCityName:"Hyderabad",myCityElevation:505}
const {myCityName: newCityName, myCityElevation:newCityElevation} = myCityObj;
console.log(newCityName);
console.log(newCityElevation);



Reference:

No comments:

Post a Comment