ES6 Destructuring Assignment
Learning about destructuring reminded me of a classic problem:
Swap the values of two variables a and b without using a third variable.
var a = 10,
b = 20;
a = {
a: a,
b: b
};
b = a.a;
a = a.b;
console.log(a) //20
console.log(b) //10
var a = 10,
b = 20;
a = [a,b]
b = a[0];
a = a[1];
console.log(a) //20
console.log(b) //10
There’s also a tricky one-liner:
var a = 10,
b = 20;
a=[b,b=a][0];
console.log(a) //20
console.log(b) //10
Now with destructuring assignment, it’s much cleaner:
var a=10;
var b=20;
[a,b]=[b,a];
console.log(a) //20
console.log(b) //10
Pretty neat, right?
Array Destructuring
What is Destructuring?
In the past, we assigned variables like this:
var foo1 =1;
var foo2 =2;
var foo3 =3;
console.log(foo1); //1
console.log(foo2); //2
console.log(foo3); //3
In ES6, we can do this:
var [foo1,foo2,foo3]=[1,2,3]
console.log(foo1); //1
console.log(foo2); //2
console.log(foo3); //3
Note: The left and right sides must have the same structure.
What if we only want to assign a subset of variables?
var [,,foo3]=[1,2,3]
console.log(foo3); //3
var [,foo2,]=[1,2,3]
console.log(foo2); //2
What if there’s no corresponding value?
var [foo1,foo2,foo3]=[1,2]
console.log(foo1); //1
console.log(foo2); //2
console.log(foo3); //undefined
var [foo1,foo2]=[1,2,3]
console.log(foo1); //1
console.log(foo2); //2
Rest parameters (spread operator …) are supported:
var [foo1,...foo2]=[1,2,3,4,5]
console.log(foo1); //1
console.log(foo2); //[2,3,4,5]
Note: Using another parameter after a rest parameter will cause an error:
var [foo1,...foo2,foo3]=[1,2,3,4,5] // Error
Object Destructuring
Object destructuring is very similar to array destructuring.
In the past, we got object property values like this:
var obj={
foo1:1,
foo2:2,
foo3:3,
}
var foo1=obj.foo1; //1
var foo2=obj.foo2; //2
var foo3=obj.foo3; //3
With destructuring:
var obj={
foo1:1,
foo2:2,
foo3:3,
}
var {foo1,foo2,foo3}=obj;
console.log(foo1); //1
console.log(foo2); //2
console.log(foo3); //3
Just write the property names on the left side, and they get assigned to variables with the same names.
What if you don’t want the variable name to match the property name?
var obj={
foo1:1,
foo2:2,
foo3:3,
}
var {foo1:bar1,foo2:bar2,foo3:bar3}=obj;
console.log(bar1); //1
console.log(bar2); //2
console.log(bar3); //3
If there’s no matching property, it will also be undefined:
var obj={
foo1:1,
}
var {foo1,foo2}=obj;
console.log(foo1); //1
console.log(foo2); //undefined