ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called deconstruction. When it is not an object or array, it will first try to convert the content to the right of the equals sign into an object. Therefore, it can also be used to deconstruct strings, Bores and values. This article briefly summarizes the array, object, string, Boolean and numerical values, function parameters and other deconstruction assignment.

Array destruct assignment

The left and right patterns must match. If they do not match, the value will be undefined or an error will be reported. However, incomplete deconstruction can also be performed, as shown in the following example:

let [foo, [[bar], baz]] = [1, [[2], 3]]; //foo:1 bar:2 baz:3 let [ , , third] = ["foo", "bar", "baz"]; //third:baz let [x, , y] = [1, 2, 3]; //x:1 y:3 let [head, ...tail] = [1, 2, 3, 4]; //head:1 tail:[2,3,4] let [x, y...z] = ['a']; //head:1 tail:[2,3,4] let [x, y...z] = ['a']; // let [foo] = []; // let [foo] = []; let [bar, foo] = [1]; // foo:undefined // let [x, y] = [1, 2, 3]; // x:1 y:2 let [a, [b], d] = [1, [2, 3], 4]; // a:1 b:2 d:4Copy the code

A destruct error occurs when the right side of the equals sign is not an array:

let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
Copy the code

Destruct assignment allows default values to be used. Default values are valid only if the value is strictly equal to undefined during the destruct process, even if it is equal to null. If the default value is an expression, the expression will be evaluated only when it is used. Then the expression will not be evaluated, for example:

let [foo = true] = []; // foo:true let [x, y = 'b'] = ['a']; // x:'a' y:'b' let [x, y = 'b'] = ['a', undefined]; // x:'a' y:'b' let [x = 1] = [undefined]; // x:1 let [x = 1] = [null]; // x:null function f() { console.log('aaa'); } let [x = f()] = [1]; // x:1, the function f does not execute, because x can be directly taken to 1Copy the code

2. Object deconstruction assignment

Array destruct assignment is determined by order, but the object is unordered, so a successful assignment must require the variable to be the same as the object’s attribute name. If not, the value is undefined, or the value is set to be the same as the attribute name using key-value pairs, as follows:

let { bar, foo } = { foo: 'aaa', bar: 'bbb' }; // bar:'bbb' foo:'aaa' let { baz } = { foo: 'aaa', bar: 'bbb' }; // baz:undefined let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; // baz:'aaa' let obj = { first: 'hello', last: 'world' }; let { first: f, last: l } = obj; // f:'hello' l:'world' // Let {bar:bar, foo:foo} = {foo: 'aaa', bar: 'BBB'};Copy the code

We can easily assign functions of objects to variables by destructuring them:

let {sin,cos,log} = Math
Copy the code

Destruct assignment of nested structures:

const node = {
  loc: {
    start: {
      line: 1,
      column: 5
    }
  }
};

let { loc, loc: { start }, loc: { start: { line }} } = node;
// loc:Object {start: Object}  start:Object {line: 1, column: 5}  line:1
Copy the code

Like arrays, objects can have default values, which are valid only if they are strictly equal to undefined:

var {x = 3} = {};
// x:3

var {x, y = 5} = {x: 1};
// x:1  y:5

var {x: y = 3} = {};
// y:3

var {x: y = 3} = {x: 5};
// y:5

var { message: msg = 'Something went wrong' } = {};
// msg: "Something went wrong"

var {x = 3} = {x: undefined};
// x:3

var {x = 3} = {x: null};
// x:null
Copy the code

If a variable has been declared, use parentheses to enclose both sides of the equation, otherwise it will be considered a code block and cause an error:

let x; {x} = {x: 1}; // SyntaxError: syntax error: ({x} = {x: 1})Copy the code

String deconstruction assignment

Before deconstruction, the string is converted to an array-like object:

const [a, b, c, d, e] = 'hello'; // a: "h" // b: "e" // c: "l" // d: "l" // e: "o"Copy the code

Array-like objects have a length attribute, so they can be destructively assigned:

let {length:len} = 'hello';
// len:5
Copy the code

4. Deconstruction of values and Boolean values

Strings, values, and bools are converted to objects. For example, they all have toString methods, which can be destructively assigned:

let {toString: s} = 123;
s === Number.prototype.toString  /true

let {toString: s} = true;
s === Boolean.prototype.toString  //true
Copy the code

5. Deconstruction assignment of function parameters

Function arguments can also be destructively assigned. Destructively assigned makes it easier to use variables passed into functions, to set default values for function arguments, and to call functions without passing in arguments, as shown in the following example:

function add([x, y]){ return x + y; } console.log(add([1, 2])); / / 3Copy the code

Set default values for function arguments:

function move({x = 0, y = 0} = {}) { return [x, y]; } console.log(move({x: 3, y: 8})); // [3, 8] console.log(move({x: 3})); // [3, 0] console.log(move({})); // [0, 0] console.log(move()); / / [0, 0]Copy the code

Deconstruct the purpose of assignment

1. Swap variable values

let x = 1;
let y = 2;
[x, y] = [y, x];
Copy the code

2. The function returns multiple values

Multiple values returned by a function can be easily retrieved by destructing assignment, but multiple values need to be placed in an array or object within the function.

function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();
Copy the code

3. Definition of function parameters

Destructuring assignment makes it easy to match a set of parameters to variable names:

function f([x, y, z]) { return x + y + z } console.log(f([1, 2, 3])); // Print out 6Copy the code

4. Extract JSON data

Deconstructing assignment makes it easy to extract data from JSON objects:

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number); //42 'OK' [867,5309]
Copy the code

5. Default values of function parameters

The default value of the specified argument, avoids the within the function body writing var foo = config. The foo | | ‘default foo’ statements like this:

jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};
Copy the code

6. Traverse the Map structure

Deconstructing assignment makes it easier to iterate over a Map’s key name or value:

For (let [key] of map) {//... } for (let [,value] of map) {//... }Copy the code

7. Input the specified method of the module

When a module is loaded, it is often necessary to specify which methods to input, and destructing assignment makes the input statements very clear

const { SourceMapConsumer, SourceNode } = require("source-map");
Copy the code

Reference: ES6 tutorial – Netpath: Variable deconstruction assignment