Easy Tutorial
❮ Programmer Without Network Python Yield Used Analysis ❯

2.2 ES6 Destructuring Assignment

Category ES6 Tutorial

Overview

Destructuring assignment is an extension of the assignment operator.

It is a pattern matching for arrays or objects, and then assigns values to the variables within.

In terms of code writing, it is concise and readable, with clearer semantics; it also facilitates the retrieval of data fields in complex objects.


Destructuring Models

In destructuring, the following two parts are involved:


Array Model Destructuring (Array)

Basic

let [a, b, c] = [1, 2, 3];
// a = 1
// b = 2
// c = 3

Nested

let [a, [[b], c]] = [1, [[2], 3]];
// a = 1
// b = 2
// c = 3

Omissible

let [a, , b] = [1, 2, 3];
// a = 1
// b = 3

Partial Destructuring

let [a = 1, b] = []; // a = 1, b = undefined

Rest Operator

let [a, ...b] = [1, 2, 3];
//a = 1
//b = [2, 3]

Strings, etc.

In array destructuring, if the target of destructuring is an iterable object, destructuring assignment can be performed. Iterable objects are data that implement the Iterator interface.

let [a, b, c, d, e] = 'hello';
// a = 'h'
// b = 'e'
// c = 'l'
// d = 'l'
// e = 'o'

Destructuring Default Values

let [a = 2] = [undefined]; // a = 2

When the destructuring pattern has a match, and the match result is undefined, the default value is triggered as the return result.

let [a = 3, b = a] = [];     // a = 3, b = 3
let [a = 3, b = a] = [1];    // a = 1, b = 1
let [a = 3, b = a] = [1, 2]; // a = 1, b = 2

Object Model Destructuring (Object)

Basic

let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
// foo = 'aaa'
// bar = 'bbb'

let { baz : foo } = { baz : 'ddd' };
// foo = 'ddd'

Nested and Omissible

let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, { y }] } = obj;
// x = 'hello'
// y = 'world'
let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, {  }] } = obj;
// x = 'hello'

Partial Destructuring

let obj = {p: [{y: 'world'}] };
let {p: [{ y }, x ] } = obj;
// x = undefined
// y = 'world'

Rest Operator

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
// a = 10
// b = 20
// rest = {c: 30, d: 40}

Destructuring Default Values

let {a = 10, b = 5} = {a: 3};
// a = 3; b = 5;
let {a: aa = 10, b: bb = 5} = {a: 3};
// aa = 3; bb = 5;

#

-

** Xiao Lan

**

❮ Programmer Without Network Python Yield Used Analysis ❯