Es6 Destructuring
// ES6 - Destructuring
This feature gives us ability to get elements from an array and assign them
to variables.
var [a, b] = [1, 2];
var [a, ,b] = [1, 2, 3]; // a is 1, and b is 3, and 2 is ignored.
This also extends to objects as well. We use square brackets to destructure
things out of arrays, and we use curly braces to destructure things out of
objects:
var [a, b] = {a: 2, b: 3};
In the above code, we have an object with properties a and b. If we just want
to grab a variable for each of those properties, we can use curly braces instead.
function getPerson() {
return {
name: 'Jack',
age: 22
}
}
var {name, age} = getPerson();
Destructuring also work for function parameters:
function foo({name, age}) {
return name + ' ' + age;
}
foo({name: 'khai', age: 42, kids: 2});
In the above code, the function foo is expected to be invoked with an object
with two properties (name and age). It gets these properties from the object
and made them available as variables for our function.
This is really useful if we are looking at functions that takes an object and
we want to know what properties we particularly care about.
page revision: 1, last edited: 19 Feb 2017 16:31