JavaScript: Destructuring Assignment
New in JS2015.
Destructuring Assignment lets you assign values in a array or object to variables, in a convenient way.
Syntax
let [x, y] =
[3,4]
;- x is 3, y is 4.
let [x,, z] = [3,4,5];
- x is 3, z is 5.
let [x=9, y=10] =
[3,4]
;- with default for each slot. (if right-hand-side has less items)
let [a, b,...c] = [1,2,3,4,5];
-
a is 1, b is 2, c is
[3,4,5]
let [...y] = [1,2,3,4,5];
-
y is
[1,2,3,4,5]
let [,...y] = [1,2,3,4,5];
-
y is
[2,3,4,5]
let {b: x} = {a:1, b:2, c:3 };
- x is 2
let {d: x = 9} = {a:1, b:2, c:3 };
- x is 9
let {a, b, c} = {a:1, b:2, c:3 };
- a is 1, b is 2, c is 3. Order need not match.
let {b} = {a:1, b:2, c:3 };
- b is 2
let {c, b:[x, y]} = {a:1, b:[2,4], c:3 };
- c is 3, x is 2, y is 4
let { c, ...restProperties } = { a:1, b:2, c:3 };
-
New in JS2018.
c is 3. restProperties is
{ a:1, b:2 }
Destructure Array Examples
For example, let [a, b, c] = [3,4,6];
.
let [a, b, c] = [3, 4, 6]; console.log(a, b, c); // 3 4 6
Destructure nested array:
let [a, [b], c] = [3, [4], 6]; console.log(a, b, c); // 3 4 6
Destructure array, skip elements:
let [a, , c] = [1, 2, 3, 4]; console.log(a, c); // 1 3
Destructure array of unknown length. Capture rest elements as a array:
let [a, b, ...c] = [1, 2, 3, 4, 5]; console.log(a, b, c); // 1 2 [3,4,5]
let [, ...x] = [1, 2, 3, 4, 5]; console.log(x); // [2,3,4,5]
let [...y] = [1, 2, 3, 4]; console.log(y); // [1,2,3,4]
If there are more variables than array element, any extra variable has value of undefined
.
// destructuring assignment, more variable than array element let [a,b] = [2]; console.log(a); // 2 console.log(b); // undefined
With default values:
// destructuring assignment, with default values let [a,b=3] = [2]; console.log(a); // 2 console.log(b); // 3
Destructure Object Examples
let {b: var_name} = {a:1, b:2, c:3};
// let x be the value of key b let {b: x} = {a:1, b:2, c:3 }; console.log( x ); // 2
With default value:
// let x be the value of key d. If it doesn't exist, default to 9 let {d: x = 9} = {a:1, b:2, c:3 }; console.log( x ); // 9
Key names as variable names.
let {b} = {a:1, b:2, c:3};
// using key names as var names let {a,b,c} = {a:1, b:2, c:3 }; console.log( a, b, c ); // 1 2 3
// extract key let {b} = {a:1, b:2, c:3 }; console.log( b ); // 2
Destructure with rest properties:
// destructure object with rest keys let { c, ...restProperties } = { a: 1, b: 2, c: 3 }; console.log(c); // 3 console.log(restProperties); // { a: 1, b: 2 }
Destructure nested array and object example:
// destructuring nested array/object let {c, b:[x,y]} = {a:1, b:[2,4], c:3 }; console.log(c); // 3 console.log(x); // 2 console.log(y); // 4