Monday, April 16, 2018

Destructuring assignment

We all know, most used data structures in JavaScript are Object and Array.

Destructuring asis a special syntax that allows us to “unpack” arrays or objects into a bunch of variables.

Why its allowing? Since they are more convenient. Most of the time we want to work with complex functions that have a lot of parameters, default values etc.,

Array destructuring:



let arr = ["Ilakiya", "Kannika"]

// destructuring assignment
let [firstName, surname] = arr;

alert(firstName); // Ilakiya
alert(surname);  // Kannika

See, Its very compatible. Its coming with ES6.

Here is another trick for ignoring first elements. See below...


let [, , title] = ["Test1", "Test2", "Test3", "Test4"];

alert( title ); // Test3

As you have put comma for two times, first two elements not considered here.

You can more play with this.. See below.


let user = {};
[user.name, user.surname] = "Ilyakiya My Love".split(' ');

alert(user.name); // Ilyakiya


Rest ...

You can mention multiple at a time , then go with “the rest” using three dots "..."


let [name1, name2, ...rest] = ["Test1", "Test2", "Test10", "Test11"];

alert(name1); // Test1
alert(name2); // Test2

alert(rest[0]); // Test10
alert(rest[1]); // Test11
alert(rest.length); // 2


No comments:

Post a Comment