Destructuring in Javascript ES6
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 …
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 …
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…
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…
Destructuring Arrays
Destructuring works on arrays as well…
which makes swapping variables a breeze without the use of a temp variable.