ES6 deconstruction assignment

1. Deconstruction assignment of array

let [a = 'a', b = 'b'] = ['undefined',undefined];  //[undefined, 'b'];
let [x = 1] = null  // Null because null === undefined false;

ES6 uses the strict equality operator (= = =) internally to judge whether a position has a value. The default value takes effect only if the array members are strictly equal to undefined

function fn() {
    console.log('Yes')
}
let [x = fn()] = [1];  //[x = 1] 

Because x gets the value, fn() is not executed. If let [x = fn()] = [undefined], the default value is executed, that is, fn() function;

let [x = 1, y = x] = []   // x = 1, y = 1;
let [x = 1, y = x] = [2]  // x = 2, y = 2;
let [x = 1, y = x] = [1, 2]  // x = 1, y = 2;
let [x = y, y = 1] = []   // ReferenceError: y is not defined

The last expression above reports an error because x = y uses y as the default value and Y is not declared

2. Deconstruction assignment of object

  • The deconstruction of objects has nothing to do with the order of attributes. Values are taken according to the attribute name, and k - v remains the same;
  • The deconstruction of array is related to the position of variables and takes values in order;
let {foo, bar} = {
    bar: 'aaa', 
    foo: 'bbb'
};  // foo: 'bbb'  bar: 'aaa'
let { baz } = {foo: 'aaa', bar: 'bbb'}; //undefined

If the variable baz does not have a corresponding attribute with the same name, the deconstruction fails and returns undefined. If the variable name is inconsistent with the attribute name, it should be written as follows

let {foo: baz} = { foo: 'aaa', baz: 'bbb' }; // baz:'aaa'
let { foo: foo, bar: bar} = { foo: 'aaa', bar: 'bbb' } // foo:'aaa', bar:'bbb'
let {foo: baz} = {foo:'aaa',bar: 'bbb'}  // baz: 'aaa'; foo: error:foo is not defined;

In the above code, foo is the matching pattern and baz is the variable. When it is really assigned, baz is not the pattern foo, which shows that the internal mechanism of object deconstruction assignment is to find the attribute with the same name to assign a value to the corresponding variable, and the former is really assigned, not the latter;

nested assignment
let obj = {};
let arr = [];
({ foo: obj.prop, bar: arr[0] } = {foo: 123, bar: true})  
obj //{prop:123,arr:[true]}
const obj1 = {};
const obj2 = {foo: 'bar'};
object.setPrototypeOf(obj1,obj2)  //The prototype object of obj1 is assigned to obj2
const { foo } = obj1;
foo  // "bar"
Default value

Object deconstruction can also have a default value. The default value takes effect on the condition that the attribute value of the object is strictly equal to undefined

var { x = 3 } = { x: undefined };    
x  // 3
var { x = 3 } = { x: null };
x // null
be careful:
// Incorrect writing:
let x;
{x} = {x:1}
// SyntaxError: syntax error
In the above writing method, js engine will interpret {x} as a code block, resulting in syntax errors. You should avoid {} at the beginning of the line
// Correct writing:
let x;
({x} = {x:1});
let arr = [1, 2, 3];
let {0: first, [arr.length - 1]: last} = arr;
first // 1
last  // 3

3. Deconstruction assignment of string

const [a, b, c, d, e] = 'hello';
a // 'h'
b // 'e'
c // 'l'
d // 'l'
e // 'o'
// Assign value to attribute deconstruction
let { length: len } = 'hello';
len // 5

4. Deconstruction assignment of numeric and Boolean values

let {toString : s} = 123;
s === Number.prototype.toString;  // true;
let {toString: s} = true;
s === Boolean.prototype.toString  // true;
let {prop: s} = undefined;    // TypeError;
let {prop: y} = null;         // TypeError;

During deconstruction assignment, the value on the right of the equal sign is not an array or object. First convert it into an object. undefined and null cannot be converted into an object, so deconstruction assignment fails.

5. Deconstruction assignment of function parameters

[[1, 2], [3, 4]].map(([a, b]) => a + b);  //[3, 7]

Deconstruction of function parameters can also use default values

function move({x = 0, y = 0} = {}) {
    return [x, y]
}
move({x: 3, y: 8});  // [3, 8]
move({x: 3});     //[3, 0]
move({});         //[0, 0]
move();           //[0, 0]
function move({x, y} = {x: 0, y: 0}) {
    return [x, y];
}
move({x; 3, y: 8});  //[3, 8];
move({x: 3})  //[3, undefined];
move({})    //[undefined, undefined];
move()      //[undefined, undefined];

The above code specifies the default value for the move parameter instead of x and y,

Default value of undefined trigger function parameter
[1, undefined, 3].map((x = 'yes') => x);   //[1, 'yes', 3]

Deconstruction assignment purpose

  • Exchange values of variables
let x = 1;
let y = 2;
[x, y] = [y, x];
  • Returns multiple values from a function
// Returns an array
function example() {
    return [1, 2, 3]
}
let [a, b, c] = example();
// Returns an object
function example() {
    return {
        foo: 1,
        bar: 2
    }
}
let {foo, bar} = example();
  • Definition of function parameters
// A parameter is an ordered set of 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});
  • Extract JSON data
let jsonData = {
    id: 42,
    status: 'ok',
    data: [1, 2]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);      
// 42, 'ok', [1, 2]
  • Traverse Map structure
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for(let [key, value] of map) {
    console.log(key + 'is' + 'value')
}
// first is hello
// second is world
Get only key names
// Get only key names
for (let [key] of map){
    // ...
}
// Get key values only
for (let [, value] of map) {
    // ...
}

Keywords: Javascript

Added by jumpfroggy on Sun, 26 Dec 2021 20:31:02 +0200