Destructuring in ES6
Over the years there have been many requests from programmers for features to be added to JavaScript. In the ECMAScript version 6 aka ES6 a lot of new features were added. Destructuring is one of the notable new features in the language. In this article I will discuss destructing, its advantages, usages, and various related aspects.
In my previous articles on JavaScript I always encouraged you to use NodeJs to code. The suggestion is the same for this one too. Using NodeJs to practice JavaScript code does not make the example codes shown in this article unusable in browsers. I am not going to use any NodeJs or browser specific API in articles. So, you are free to practice the code both in browsers or NodeJs environments. But, remember to use latest browsers or NodeJs to practice ES6 codes. If you want to run ES6 codes in older versions of browsers or NodeJs you can use Babel to transpile the code first.
What is Destructuring
Destructuring is somewhat the opposite of constructing, but it is not exactly opposite (destructuring is not destructing). Destructuring is an assignment syntax that makes it very easy to unpack variables from arrays, iterables and objects into distinct variables. So, it can be safely said that destructuring is a way of unpacking values from arrays, objects, iterables into separate variables with easy and concise syntax.
Note: Maps and Sets are also iterables in ES6.
Destructuring in Older Versions of JavaScript
Let's say that we have an array of numbers like below:
var nums = [3.1413, 6.03, 5, 100]
Now, if we want to put all those values in separate variables we have code like below:
var nums = [3.1413, 6.03, 5, 100];
var v1 = nums[0];
var v2 = nums[1];
var v3 = nums[2];
var v4 = nums[3];
The array could be handmade or created dynamically:
var chars = "a b c d".split(" ")
We could also do the same with objects. Let's say we have an object that describes a person like below:
var po = {name: "John", age: 25, profession: "Doctor"}
We could put the name, age, and profession in individual variables in the following way:
var p_name = po.name;
var p_age = po.age;
var p_profession = po.profession;
Or with subscript notation:
var p_name = po['name'];
var p_age = po['age'];
var p_profession = po['profession'];
For iterables the operation could be more complex.
Destructuring in ES6
In ES6 the operation has become a lot easier. Let's see how we can destructure the first array of numbers.
var [v1, v1, v3, v4] = nums;
Or
var [v1, v1, v3, v4] = [3.1413, 6.03, 5, 100];
A string can be iterated and we can get individual characters for the iteration. So, we can destructure a string in the same way.
var a_str = "AbCd";
var [c1, c2, c3, c4] = a_str;
In all the above examples in this section v1, v2, v3, v4, c1, c2, c3, c4 are individual variables. You can try outputting the values with console.log() function.
With the help of the destructuring feature in ES6 we can do more work with less and cleaner code. For iterable and arrays we use an opening and a closing square bracket with a list of variable names separated with commas to destructure values into variables. So, it is more like array notation.
For objects we use a pair of curly braces to enclose the variable names. We provide the property name of the object that we want to extract value from and the variable name separated by a colon. We separate these pairs with commas. So, it is like object notation. But, instead of values after a colon we provide the variable name in which we want to extract value from the relevant property. See this example:
var po = {name: "John", age: 25, profession: "Doctor"};
var {name: p_name, age: p_age, profession: p_profession} = po;
console.log(p_name);
So, it is easy and concise to extract values into variables with ES6 destructuring syntax.
Default Values in Destructuring
What happens when the number of variables on the left hand side exceeds the length of the array or iterable on right hand side? What happens if the property we are specifying on the left hand side does not exist in the object on the right hand side? Let's see with an example:
var o = {n:5};
var {n: var1, p: var2} = o;
console.log("n="+var1);
console.log("p="+var2);
Outputs:
n=5
p=undefined
So, if we provide a non existent property name or go beyond the last index of the array we will get undefined as the value. So, we need to provide default values sometimes to stay on the safe side. Providing default value is very simple. You need to put an equal sign after the variable name and the default value like below:
var o = {n:5};
var {n: var1, p: var2=100} = o;
console.log("n="+var1);
console.log("p="+var2);
Now it outputs:
n=5
p=100
It is similar for arrays and iterables too:
var [a, b=5] = [1];
console.log(b);
Outputs:
5
The default value is also triggered when the real value after unpacking is undefined. Let's see with an example:
var o = {n:5, p: undefined};
var {n: var1, p: var2=100} = o;
console.log("n="+var1);
console.log("p="+var2);
Outputs:
n=5
p=100
This time the property p exists in the object o but the default value 100 was taken instead of the value stored in p.
Conclusion
ES6 has fulfilled various demands of JavaScript programmers that were unfulfilled for many years. ES6 made it possible to make code cleaner and more concise. It made JavaScript programmers more powerful and more productive. Remember the famous saying: "With great power comes with great responsibility". Do not overuse the features of ES6 so that it become a bottleneck and overkill for your program. Think about destructuring, for example, that it provides ways to extract values from objects, arrays, iterables into variables. But we usually do not want to create a lot of variables—that was the reason arrays and objects came. Still sometimes we need to extract values into variables and a concise syntax is of a great help. So, use it with care and be more productive with less code.
Next article: coming soon! |
About the Author
My name is Md. Sabuj Sarker. I am a Software Engineer, Trainer and Writer. I have over 10 years of experience in software development, web design and development, training, writing and some other cool stuff including few years of experience in mobile application development. I am also an open source contributor. Visit my github repository with username SabujXi.
Recent Stories
Top DiscoverSDK Experts
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}
{{CommentsModel.TotalCount}} Comments
Your Comment