ES6 deconstruction assignment

Deconstruction assignment is an extension of assignment operator, which can extract attributes/values from objects/arrays and assign them to other variables.

 

1. Deconstruction assignment of arrays

1. Basic usage

As long as the patterns on both sides of the equal sign are the same, the variables on the left are assigned corresponding values.

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

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

Deconstruction assignment applies not only to let commands, but also to var and const commands.

 

2. Default values

Deconstruction assignments allow default values to be specified.

var [a = 1] = [];
a  // 1

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

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

Because ES6 uses strict equality operators (====) internally, it determines whether a location is worth it. Therefore, if an array member is not strictly undefined, the default value will not take effect.

var [a = 1] = [undefined];
a // 1

var [a = 1] = [null]; a // null

In the above code, if an array member is null, the default value will not take effect because null is not strictly equal to undefined.

Default values can refer to other variables that deconstruct assignments, but that variable must have been declared.

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

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

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

let [a = y, b = 1] = [];
// ReferenceError

The last expression above reported an error because b was not declared when a used the default value b.

 

2. Deconstruction and Assignment of Objects

1. Basic usage

Deconstruction can be used not only for arrays, but also for objects.

var { a, b } = { a: "aaa", b: "bbb" };
a // "aaa"
b // "bbb"

The difference between object deconstruction and array structure:

  • The elements of an array are arranged in order, and the value of a variable is determined by its position.
  • The attributes of objects have no order. Variables must have the same name as attributes in order to get the correct values.
var { a, b } = { b: "bbb", a: "aaa" };
b // "bbb"
a // "aaa"

var { c } = { a: "aaa", b: "bbb" }; c // undefined

If the variable name is inconsistent with the attribute name, you need to write as follows:

var { a: x } = { a: "aaa", b: "bbb" };
x // "aaa"

let obj = { a: "aaa", b: "bbb" }; let { a: x, b: y } = obj; x // "aaa" y // "bbb"

The internal mechanism of object deconstruction assignment is to find the same name attribute first, and then assign the corresponding variables. It is the latter, not the former, that is really assigned.

So the second code above will report an error if it outputs a or b directly:

let obj = { a: "aaa", b: "bbb" };
let { a: x, b: y } = obj;
a // error: a is not defined
b // error: b is not defined

In the above code, the variables x and y are really assigned, not the patterns a and b.

Note that variables cannot be re-declared for let and const, so once the assigned variable has been declared before, it will report an error.

let a;
const obj = { a:"aaa" };
{a} = obj;
a // SyntaxError: Unexpected token =

Solution: Add "()" to the second line of code

let a;
const obj = { a:"aaa" };
({a} = obj);
a // "aaa"

In the above code, the parser interprets the first braces as a block of code, not an assignment statement.

Like arrays, deconstruction can also be used for objects with nested structures.

var obj = {
    A: {
        a: {
            x: 1,
        }
    }
};
var { A: { a: { x }} } = obj;
A // undefined
a // undefined
x // 1

In the above code, only x is a variable, A and a are schemas and will not be assigned.

 

2. Default values

Object deconstruction can also specify default values.

var {a = 1} = {};
a // 1

var {a, b = 2} = {a: 1}; a // 1 b // 2
var { a: x = 1 } = {}; x // 1

The default value takes effect only if the attribute value of the object is strictly equal to undefined.

var {a = 1} = {a: undefined};
a // 1

var {a = 3} = {a: null}; a // null

If you write braces at the beginning, JavaScript interprets them as blocks of code.

var x;
{x} = {x: 1};
// SyntaxError: syntax error

Writing of the above code will cause errors because the JavaScript engine interprets {x} as a block of code, resulting in syntax errors.

//  Solution
({x} = {x: 1});

 

3. String deconstruction assignment

Strings can also deconstruct assignments because strings are converted into an array-like object.

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

Objects like arrays have a length attribute, so you can also deconstruct and assign values to this attribute.

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

 

4. Deconstruction and Assignment of Numbers and Boolean Values

When deconstructing assignment, if the right-hand side of the equal sign is a value and a Boolean value, it will first be converted to an object.

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

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

In the code above, both the wrapper object of the value and the Boolean value have toString attributes, so the variable s can get the value.

The rule of deconstruction assignment is that as long as the value on the right side of the equal sign is not an object, it is first converted to an object.

Because undefined and null cannot be converted to objects, deconstruction assignment of them will cause errors.

let { prop: x } = undefined; // TypeError

let { prop: y } = null; // TypeError

 

5. Deconstruction and Assignment of Functional Parameters

Function parameters can also be assigned using deconstruction.

function add([x, y]){
return x + y;
}
add([1, 2]); // 3

Default values can also be used to deconstruct function parameters.

function iPhone(a = "x", b = "iOS11", c = "A11"){
    console.log(a, b, c);
}
iPhone(a = "xs", b = "iOS12"); // xs iOS12 A11

 

6. The problem of parentheses

1. Failure to use parentheses

(1) Variable declaration statements should not have parentheses.

//  Full error reporting
var [(a)] = [1];
var {x: (c)} = {};
var ({x: c}) = {};
var {(x: c)} = {};
var {(x): c} = {};
var { o: ({ p: p }) } = { o: { p: 2 } };

(2) In function parameters, the mode cannot be parenthesized.

//  Report errors
function f([(z)]) { return z; } 

(3) In assignment statements, the whole pattern, or one layer of nested pattern, cannot be placed in parentheses.

//  Full error reporting
({ p: a }) = { p: 42 };
([a]) = [5];
  • The above code places the whole pattern in parentheses, causing an error.

 

2. Use of parentheses

  • There is only one case where parentheses can be used: the non-schematic part of the assignment statement.
[(b)] = [3]; //  Correct
({ p: (d) } = {}); //  Correct
[(parseInt.prop)] = [3]; //  Correct
  • The above three lines of statements can be executed correctly, because first of all, they are assignment statements, not declaration statements.
  • Next, their parentheses are not part of the pattern.
  • In the first line, the pattern takes the first member of the array, independent of parentheses.
  • In the second line, the pattern is p, not d.
  • The third line is the same as the first line.

 

VII. Application of Deconstruction Assignment

1. Values of Exchange Variables

[x, y] = [y, x];
// Exchange variables x and y Value

 

2. Return multiple values from a function

//  Returns an array
function arr() {
  return [1, 2, 3];
}
var [a, b, c] = arr();
// Return an object function obj() {   return {     a: 1,     b: 2   }; } var { a, b } = obj();

 

3. Definition of Functional Parameters

//  A parameter is a set of ordered values
function f([x, y, z]) { ... }
f([1, 2, 3]);
// A parameter is an unordered set of values function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});

 

4. Extracting JSON Data

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

Keywords: PHP Attribute Javascript JSON

Added by Pro Ninja on Fri, 12 Jul 2019 21:40:33 +0300