Detailed explanation of JS ES6 variable destructuring assignment

Detailed explanation of JS ES6 variable destructuring assignment

1. What is deconstruction?

ES6 allows you to extract values ​​from arrays and objects and assign values ​​to variables according to a certain pattern, which is called destructuring. It is more concise, compact, and clear in syntax than what ES5 provides. Not only does it reduce the amount of code you write, it can fundamentally change the way you code.

2. Array Destructuring

Previously, to assign values ​​to variables, we could only specify the values ​​directly, such as

let a = 1;
let b = 2; 
let c = 3;

Now you can use array destructuring to assign values

let [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1, 2, 3

This is the most basic type of array deconstruction usage, you can also deconstruct object arrays

// Object array deconstruction let [a, b, c] = [{name: 'jacky'}, {name: 'monkey'}, {name: 'houge'}];
console.log(a, b, c); // {name: 'jacky'}, {name: 'monkey'}, {name: 'houge'}

3. Unification of array mode and assignment mode

This can be understood as the forms on the left and right sides of the equal sign must be unified. If they are not unified, the deconstruction will fail.

let [a, [b, c], d] = [1, [2, 3], 4];
console.log(a, b, c, d); // 1 2 3 4

 // Extract all values ​​except the second and third let [a, , , d] = [1, 2, 3, 4];
console.log(a, d); //1 4
    
let [a, ...b] = [1, 2, 3, 4];
console.log(a, b); // 1 [2, 3, 4]
        
let [a, , , ...d] = [1, 2, 3, 4, 5];
console.log(a, d); // 1 [4, 5]
If the deconstruction is unsuccessful, the value of the variable is equal to undefined

let [a, b, c] = [2, 3];
console.log(a, b, c); // 2 3 undefined

let [c] = [];
console.log(c); // undefined

If the deconstruction is unsuccessful, the value of the variable is equal to undefined

let [a, b, c] = [2, 3];
console.log(a, b, c); // 2 3 undefined

let [c] = [];
console.log(c); // undefined

The above is a case of complete deconstruction. There is also an incomplete deconstruction, that is, the pattern on the left side of the equal sign only matches a part of the array on the right side of the equal sign, and the deconstruction can still succeed.

let [x, y] = [1, 2, 3]; 
console.log(x, y); // 1 2

let [a, [b], d] = [1, [2, 3], 4];
console.log(a, b, d); // 1 2 4

4. Destructuring default values

Destructuring assignment allows specifying default values.

let [a, b=2] = [1];
console.log(a, b); // 1 2

let [a=1, b=2, c, d=13] = [10, 11, 12];
console.log(a, b, c, d); // 10 11 12 13

5. Object deconstruction assignment

Object destructuring differs from array destructuring in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position; however, the properties of an object have no order, and the variable must have the same name as the property to obtain the correct value.

// The internal mechanism of object deconstruction assignment is to first find the attribute with the same name, and then assign it to the corresponding variable. It is the latter, not the former, that is actually assigned.
let obj = { a: "aaa", b: "bbb" };
let { a: x, b: y } = obj; 
console.log(x, y); // aaa bbb

let { a, b } = { a: 'aaa', b: 'bbb' };
console.log(a, b); // aaa bbb

// Not in order let { b, a } = { a: 'test1', b: 'test2' }
console.log(a, b) // test1 test2


// Nested destructuring let { obj: { name }} = { obj: { name: 'jacky', age: '22' } }
console.log(name) // jacky

// Slightly more complex nested let obj = {
    p: [
        'Hello',
        { y: 'World' }
    ]
};

let { p: [x, { y }] } = obj;
console.log(x, y); // Hello World

If the variable name does not match the attribute name, it must be written as follows.

var { foo: rename } = { foo: "aaa",bar: "bbb" };
console.log(rename); // aaa
console.log(foo); // Uncaught ReferenceError: foo is not defined

If the variable is defined before destructuring, there will be problems with destructuring at this time. The following is incorrect code, and the compilation will report an error (because the js engine will understand {a} as a code block, resulting in a syntax error. This problem can only be solved by not writing the curly braces at the beginning of the line to prevent js from interpreting it as a code block)

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

To solve the error and make the program work properly, just add a parenthesis outside the deconstruction statement.

let a;
let obj = { a: "aaa" };
( {a} = obj );
console.log(a); // aaa

6. Function parameters

Function parameters can also be assigned using destructuring.

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3

Destructuring of function parameters can also use default values.

function fn(x, y = 7) {
    return x + y;
}
console.log(fn(3)); // 10

7. String Destructuring

The string is converted into an array-like object.

const [a, b, c, d, e, f] = "hello";
console.log(a); //h
console.log(b); //e
console.log(c); //l
console.log(d); //l
console.log(e); //o
console.log(f); //undefined

8. Destructuring assignment of numeric and Boolean values

When destructuring and assigning values, if the right side of the equal sign is a numeric value or a Boolean value, it will be converted to an object first.

let { toString: s } = 0;
console.log(s === Number.prototype.toString); // true

let { toString: s } = true;
console.log(s === Boolean.prototype.toString); // true

The rule of destructuring assignment is that as long as the value on the right side of the equal sign is not an object or an array, it is first converted to an object. Since undefined and null cannot be converted into objects, destructuring and assigning them will result in errors.

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

9. Application of destructuring assignment

1. Swap the values ​​of variables

The usual method of swapping two variables requires an additional temporary variable, as follows

let a = 1;
let b = 2;
let temp;

temp = a;
a = b;
b = temp;

console.log(a, b); // 2 1

If you use ES6 destructuring assignment, it will become very concise

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

console.log(a, b); // 2 1

2. Return multiple values ​​from a function

A function can only return one value. If you want to return multiple values, you can only return them in an array or object. With destructuring assignment, it is very convenient to extract these values.

// Return an array function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// Return an object function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

3. Accessing elements in an array

There is a scenario, such as there is an array (which may be empty). and you want to access the first, second, or nth item of an array, but if the item does not exist, use a specified default value.

Usually the length property of the array is used to determine

const list = [];

let firstItem = 'hello';
if (list.length > 0) {
    firstItem = list[0];
}

console.log(firstItem); // hello

If ES6 destructuring assignment is used to implement the above logic

const list = [];
const [firstItem = 'hello'] = list;

console.log(firstItem); // 'hello'

4. Extract JSON data

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]

5. Traversing the Map structure

Any object that implements the Iterator interface can be traversed using a for...of loop. The Map structure natively supports the Iterator interface, and it is very convenient to obtain key names and key values ​​by combining variable deconstruction assignment.

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

If you only want to get the key name, or only want to get the key value, you can write it as follows.

// Get the key name for (let [key] of map) {
  // ...
}

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

The above is a detailed explanation of the deconstruction assignment of JS ES6 variables. For more information about the deconstruction assignment of JS ES6 variables, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Summary of common usage of javascript destructuring assignment under ES6
  • An article to help you understand JavaScript destructuring assignment
  • A practical guide to JavaScript destructuring assignment
  • JavaScript destructuring assignment detailed explanation
  • JS ES new feature of variable decoupling assignment
  • 5 common scenarios and examples of JavaScript destructuring assignment
  • Detailed description of shallow copy and deep copy in js
  • JavaScript assignment, the difference between shallow copy and deep copy

<<:  10 SQL statement optimization techniques to improve MYSQL query efficiency

>>:  How to deploy Confluence and jira-software in Docker

Recommend

Detailed explanation of the loading rules of the require method in node.js

Loading rules of require method Prioritize loadin...

React implements import and export of Excel files

Table of contents Presentation Layer Business Lay...

NodeJs high memory usage troubleshooting actual combat record

Preface This is an investigation caused by the ex...

mysql5.5 installation graphic tutorial under win7

MySQL installation is relatively simple, usually ...

A brief discussion on the solution to excessive data in ElementUI el-select

Table of contents 1. Scenario Description 2. Solu...

CentOS7 installation GUI interface and remote connection implementation

Use the browser (webdriver)-based selenium techno...

Detailed steps to install Mysql5.7.19 using yum on Centos7

There is no mysql by default in the yum source of...

Summary of the use of special operators in MySql

Preface There are 4 types of operators in MySQL, ...

The order of event execution in the node event loop

Table of contents Event Loop Browser environment ...

Steps to install MySQL 5.7.10 on Windows server 2008 r2

Install using the MSI installation package Downlo...

Bugs encountered when using mybatis-generator with mysql8.0.3 in IDEA

1. Add the plug-in and add the following configur...

How to deploy Spring Boot using Docker

The development of Docker technology provides a m...

Optimized implementation of count() for large MySQL tables

The following is my judgment based on the data st...