JavaScript destructuring assignment detailed explanation

JavaScript destructuring assignment detailed explanation

concept

ES6 provides a more concise assignment mode to extract values ​​from arrays and objects, which is called destructuring.

Example:

[a, b] = [50, 100];
console.log(a);
// expected output: 50
console.log(b);
// expected output: 100
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: [30, 40, 50]

Array Destructuring

Array destructuring is very simple and concise. Use an array literal on the left side of the assignment expression. Each variable name in the array literal is mapped to the same index item in the destructuring array.

What does this mean? It means that as in the following example, the items in the left array get the values ​​of the corresponding indexes of the deconstructed array on the right.

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

Declare and assign values ​​separately

You can destructure and assign values ​​separately by declaring variables

Example : Declare variables and assign values ​​to them

// declare variables let a, b;
// Then assign values ​​[a, b] = [1, 2] respectively;
console.log(a); // 1
console.log(b); // 2

Destructuring default values

If the value extracted by deconstruction is undefined, you can set a default value:

let a, b;
// Set default values ​​[a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7

In the above example, we set default values ​​for both a and b.

In this case, if the value of a or b is undefined, it will assign the default value of the setting to the corresponding variable (5 is assigned to a and 7 is assigned to b)

Swapping variable values

In the past, we exchanged two variables using

//Exchange ab
c = a;
a = b;
b = c;

Or XOR method

However, in destructuring assignment, we can swap two variable values ​​in one destructuring expression.

let a = 1;
let b = 3;
//Exchange the values ​​of a and b [a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

Deconstructing arrays returned by functions

We can directly deconstruct a function that returns an array

function c() {
  return [10, 20];
}
let a, b;
[a, b] = c();
console.log(a); // 10
console.log(b); // 20

In the above example, the return value [10, 20] of c() can be destructured on a single line of code.

Ignore return value (or skip an item)

You can selectively skip unwanted return values

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

Assign the remainder of an array to a variable

When you use array destructuring, you can assign the remainder of the assigned array to a variable.

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

In this case, b will also become an array, and the items in the array are all the remaining items.

Notice:

Be careful here that you cannot put a comma at the end. If you put an extra comma, an error will be reported.

let [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma

Nested array destructuring

Like objects, arrays can also be nested.

Example:

const color = ['#FF00FF', [255, 0, 255], 'rgb(255, 0, 255)'];
// Use nested destructuring to assign red, green and blue
// Use nested destructuring to assign red, green, blue
const [hex, [red, green, blue]] = color;
console.log(hex, red, green, blue); // #FF00FF 255 0 255

String Destructuring

In array deconstruction, if the target of deconstruction is a traversable object, deconstruction assignment can be performed. A traversable 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'
*/

Object Destructuring

Basic object deconstruction

let x = { y: 22, z: true };
let { y, z } = x; // shorthand for let {y:y,z:z} = x; console.log(y); // 22
console.log(z); // true

Assign value to new variable name

You can change the name of a variable when using object destructuring

let o = { p: 22, q: true };
let { p: foo, q: bar } = o;
console.log(foo); // 22
console.log(bar); // true

As shown in the code above, var {p: foo} = o gets the property name p of object o and assigns it to a variable named foo.

Destructuring default values

If the deconstructed object value is undefined, we can set a default value

let { a = 10, b = 5 } = { a: 3 };
console.log(a); // 3
console.log(b); // 5

Assigning a value to a new object name while providing a default value

As mentioned earlier, we assign a value to a new object name. Here we can provide a default value for the new object name. If it is not destructured, the default value will be automatically used.

let { a: aa = 10, b: bb = 5 } = { a: 3 };
console.log(aa); // 3
console.log(bb); // 5

Using array and object destructuring together

Arrays and objects can be used together in structures

const props = [
  { id: 1, name: 'Fizz' },
  { id: 2, name: 'Buzz' },
  { id: 3, name: 'FizzBuzz' },
];
const [, , { name }] = props;
console.log(name); // "FizzBuzz"

Incomplete deconstruction

let obj = {p: [{y: 'world'}] };
let {p: [{ y }, x ] } = obj; //Do not deconstruct x
// x = undefined
// y = 'world'

Assigning a rest value to an object

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
// a = 10
// b = 20
// rest = {c: 30, d: 40}

Nested object destructuring (destructuring can be ignored)

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; // ignore y
// x = 'hello'

Precautions

Be careful with destructuring of declared variables

Error demonstration:

let x;
{x} = {x: 1};

The JavaScript engine will interpret {x} as a code block, resulting in a syntax error. We should avoid writing curly braces at the beginning of the line to prevent JavaScript from interpreting it as a code block.

Correct way to write:

let x;
({x} = {x: 1});

The correct way to write it is to put the entire destructuring assignment statement in parentheses, and it will execute correctly.

Destructuring assignment of function parameters

Function parameters can also be assigned using destructuring

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

In the above code, the parameter of the add function is an array on the surface, but when passing the parameter, the array parameter is deconstructed into variables x and y. For the function, it is the same as directly passing x and y.

Uses of Deconstruction

There are many uses for destructuring assignment

Swapping the values ​​of variables

let x = 1;
let y = 2;
[x, y] = [y, x];

The above code swaps the values ​​of x and y. This is not only concise but also easy to read and has clear semantics.

Returning multiple values ​​from a function

A function can only return one value. If we want to return multiple values, we can only return these values ​​in an array or object. When we have destructuring assignment, it is as easy as taking out something from a bag to get these values ​​from an object or array.

// 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();

Extracting JSON data

Destructuring assignment is particularly useful for extracting data from JSON objects.

Example:

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

Using the above code, we can quickly retrieve the value in the JSON data

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content 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
  • 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
  • Detailed explanation of JS ES6 variable destructuring assignment
  • JavaScript assignment, the difference between shallow copy and deep copy

<<:  Sample code for implementing DIV suspension with pure CSS (fixed position)

>>:  Solutions to problems related to software package dependency reporting during installation in Linux

Recommend

Detailed tutorial on installing nacos in docker and configuring the database

Environment Preparation Docker environment MySQL ...

Share 8 CSS tools to improve web design

When one needs to edit or modify the website desi...

uniapp dynamic modification of element node style detailed explanation

Table of contents 1. Modify by binding the style ...

Use of MySQL stress testing tool Mysqlslap

1. MySQL's own stress testing tool Mysqlslap ...

HTML table tag tutorial (12): border style attribute FRAME

Use the FRAME property to control the style type ...

Linux system (Centos6.5 and above) installation jdk tutorial analysis

Article Structure 1. Preparation 2. Install Java ...

A brief analysis of the responsiveness principle and differences of Vue2.0/3.0

Preface Since vue3.0 was officially launched, man...

Vue detailed introductory notes

Table of contents 1. Introduction 2. Initial Vue ...

Vue uses WebSocket to simulate the chat function

The effect shows that two browsers simulate each ...

Tutorial on deploying the open source project Tcloud with Docker on CentOS8

1. Install Docker 1. I installed Centos7 in the v...

Solution to mysql error code 1064

If the words in the sql statement conflict with t...

Vue2 cube-ui time selector detailed explanation

Table of contents Preface 1. Demand and Effect ne...

Sample code for automatic web page refresh and automatic jump

Automatic web page refresh: Add the following code...

Example of using MySQL to count the number of different values ​​in a column

Preface The requirement implemented in this artic...