SoFunction
Updated on 2025-04-06

Structural assignment of ES6 variables in JavaScript

There are many users who have structures assigned to the variables

1. Exchange the value of the variable

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

The above code exchanges the values ​​of variable x and variable y. This writing method is not only concise, easy to read, and has very clear semantics.

2. Return multiple values ​​from the function

Functions can only return one value. If you want to return multiple values, you can only say that they are returned in an array or object. Understand deconstruction and assignment, it is very convenient to obtain these values

//Return an arrayfunction example(){
  return [1,2,3];
}
let [a,b,c] = example();
[a,b,c];  //[1,2,3]
//Return an objectfunction example(){
  return {
    foo:1,
    bar:2
  };
}
let {foo,bar} = example();
foo;  //1
bar;  //2

3. Definition of function parameters

Deconstructing assignments can easily explain a set of parameters corresponding to variable names.

//The parameters are a set of ordered valuesfunction f([x,y,z]){
  (x,y,z);
}
f([1,2,3]); //1,2,3
//The parameters are a set of unordered valuesfunction func({x,y,z}){
  (x,y,z);
}
func({z:3,y:2,x:1}); //1,2,3

4. Extract JSON data

Deconstructing assignments are especially useful for extracting data from JSON objects

let jsonData = {
  id:42,
  status:"OK",
  data:[123,456]       
} ;
let {id,status,data:number} = jsonData;
(id,status,number);  //42 "OK" (2) [123, 456]

5. The default value of function parameters

、、、

6. Traverse the Map structure

Any object that has the Iterator interface deployed can use the for... of loop traversal. The Map structure natively supports the Iterator interface, and it is very convenient to obtain names and key values ​​with deconstruction and assignment of variables.

var map = new Map();
('first','hello');
('second','world');

for(let [key,value] of map){
  (key,value);
}

//first hello
//second world

If you only want to get the key name, or just want to get the key value, you can write this way.

//Get the key namefor(let [key] of map){
  (key);
}

//first
//second
//Get key valuefor(let [,value] of map){
  (value);
}
//hello
//world

7. Method for specifying input module

When loading a module, you often need to specify the input method. Deconstructing assignments make the input statements very clear.

const {a,b} = require('source-map');

Summarize

The above is the structure assignment of ES6 variables in JavaScript introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!