Destructuring assignment

Defination

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Syntax

1
var a, b, rest;
2
[a, b] = [10, 20];
3
console.log(a); // 10
4
console.log(b); // 20
5
6
[a, b, ...rest] = [10, 20, 30, 40, 50];
7
console.log(a); // 10
8
console.log(b); // 20
9
console.log(rest); // [30, 40, 50]
10
11
({a, b} = {a: 10, b: 20});
12
console.log(a); // 10
13
console.log(b); // 20
14
15
// Stage 3 proposal
16
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
Copied!

Examples

1
// Basic variable assignment
2
var foo = ['one', 'two', 'three'];
3
4
var [one, two, three] = foo;
5
console.log(one); // "one"
6
console.log(two); // "two"
7
console.log(three); // "three"
8
// Assignment separate from declaration
9
var a, b;
10
11
[a, b] = [1, 2];
12
console.log(a); // 1
13
console.log(b); // 2
Copied!

Usage

1
const Todo = ({ content, onClick, completed }) => (
2
<li>
3
<div className="view">
4
<input onChange={onClick} className="toggle" type="checkbox" checked={completed ? 'checked' : ''} />
5
<label href="/#">{content}</label>
6
</div>
7
</li>
8
);
Copied!

References