Destructuring in Javascript ES6

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Here we have an object “john” assigned to “employee”.   If we want to extract out the property value of “name” into a variable “n”.  And the property value “age” into a variable “a”, we can do …

destructuring objects

This is equivalent to the commented lines in green.  It says take the “name” property of “employee” object and save it to variable “n”.  Similarly, take the “age” property of “employee” and save to “a”.

If you don’t mind keeping the variable name and the property name the same, you can do …

destructuring equivalent

This is just a short-cut form when the “property” field and the “variable” are named the same.  It is equivalent to …

let { name : name, age : age } = employee;

How is this useful?  Consider the function greetEmployee that destructures an object that passed to it.  Now inside the function, it has the extracted data of “name” and “age” of the “employee” object…

object destructured

You can supply a default value to the function argument like this where we pass in a new object with name “Jane” but has no age.  The function argument will use 0 as age…

default value destructuring

Destructuring Arrays

Destructuring works on arrays as well…

destructuring array

which makes swapping variables a breeze without the use of a temp variable.

destructuring swap

More ES6 features here.