Overview

Destructuring assignment is an extension of the assignment operator.

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

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


Destructuring model

In destructuring, the following two parts are involved:

    The source of destructuring, the right-hand side of the destructuring assignment expression.
  • The target of destructuring, the left-hand side of the destructuring assignment expression.

Destructuring of array model (Array)

Basic

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

Nestable

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

Ignorable

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

Incomplete 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 destructuring target is an iterable object, destructuring assignment can be performed. An iterable object is data that implements 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 result and the match result is undefined, the default value will be triggered as the returned 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
  • The match result of a and b is undefined, triggering default values:a = 3; b = a =3
  • a is normally destructured and assigned, match result: a = 1, b's match result is undefined, triggering default value:b = a =1
  • a and b are normally destructured and assigned, match result:a = 1,b = 2

Destructuring of object model (Object)

Basic

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

Nestable and ignorable

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'

Incomplete 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;