Destructuring in ES2015
Destructuring is a new way to extract values from nested objects and arrays. It was introduced as a part of ES2015 a.k.a ES6, which is new standard for ECMAScript. This blog post describes how it works with suitable examples.
Syntax
Array destructuring
Below is a simple example showcasing array destructuring.
var foo = [1, 2, 3];
// without destructuring
var x = foo[1],
y = foo[2],
z = foo[3];
// with destructuring
var [x, y, z] = foo; // x = 1, y = 2, z = 3
Object destructuring
Below is a simple example showcasing array destructuring.
var name = {first: "John", last: "Doe"};
// without destructuring
var f = name.first,
l = name.last;
// with destructuring
var {first: f, last: l} = name; // f = "John", l = "Doe"
Possible Uses
Swaping Variables
Below code will swap the values of the variables a
and b
. Without destructuring, this would require the use of a extra temporary variable.
var a = 1, b = 2;
[a, b] = [b, a]; // a = 2, b = 1
Multiple Return Values
Destructuring make it very convinient to utilize multiple return values from a function.
function foo() {
return [1, 2];
}
var [x, y] = foo(); // x = 1, y = 2
Ignoring values
Destructuring lets you select only the values you are intrested in, and ignore the remaining values.
function foo() {
return [1, 2, 3];
}
var name = {first: "John", last: "Doe"};
var [a, , b] = foo(); // a = 1, b = 3
var [x, y] = foo(); // x = 1, y = 2
var {first: f} = name; // f = "John"
Nested Destructuring
Destructuring can also be used for nested objects/arrays.
var person = {
name: {
first: "John",
last: "Doe"
},
age: 24,
married: false
};
var {name: {first: f, last: l}, age: a} = person; // f = "John", l = "Doe", a = 24
Further Reading
Destructuring and parameter handling in ECMAScript 6 – 2ality.com
Destructuring assignment – Mozilla Developer Network
Best Open Source Business Intelligence Software Helical Insight is Here