preface

Original intention: recently read “Deep Understanding Es6” this book, before did not have a good comprehensive study of Es6 grammar, but also take advantage of the phase of not busy to re-study to sort out the notes to share with you, do not like it.

For whom: Front end primary development, big guy detour.

Content structure: Basic syntax -> Syntax pros and cons -> Application scenarios

Why use deconstruction

In Es5, when we wanted to get specific data from an object or an array object, we usually did it this way. Here’s an example

let person = {
    name: "Frogman".age: 24
}

let name = person.name
let age = person.age
Copy the code

In the example above, you can see that we took the name and age attributes from the Person object and assigned them to the newly declared variables name and age. That’s fine, if there are more.

So Es6 provides deconstruction for objects and arrays, making it easier to break up data structures and get the information you need from smaller chunks. So let’s see

Object to deconstruct

let person = {
    name: "Frogman".age: 24
}
let { name, age } = person
console.log(name) / / frogman
console.log(age) / / 24
Copy the code

In the example above, the value of person.name is assigned to the name variable, and the value of person.age is assigned to the age variable. If you don’t understand the new features of objects, see my previous article, “What features do Es6 objects extend?”

Don’t forget the initialization values

If you use var, let, or const to declare deconstructing, you must initialize the value, which is the variable on the right. Let’s look at an example

var { name, age }; Let {name, age}; // Syntax throws an error const {name, age}; // Syntax throws an errorCopy the code

In the example above, we can see that there is a declaration that is used to deconstruct an assignment but does not initialize the value so an error is thrown. Var and let variables may not be initialized if they are not used for destructuring, but const variables must be initialized otherwise an error is thrown. If you don’t understand the difference between var, let, and const, read this article.

Note: An error is thrown if the value to the right of the destruct assignment is null or undefined, remember.

Deconstruction assignment

In the previous section, we have covered deconstruction, so what is a deconstruction assignment? That is, we also use destructor syntax for assigning values to variables. Here’s an example

Let person = {name: "frogman ", age: 24}; // Assign the variable ({name, age} = person); Console. log(name) // Frogman console.log(age) // 24Copy the code

In the example above, we first define the name and age variables, initialize the values, and then re-assign the name and age variables from the Person object using a deconstructed assignment method. The JavaScript engine treats curly braces as a block of code, and the syntax dictates that a block of code cannot appear on the left side of an assignment statement. Wrapping the curly braces will transform the block of code into an expression, which will enable the deconstructed assignment.

We next use destruct assignment expressions for function arguments

let name = "Wang"
let age = 18
let person = {
    name: "Frogman".age: 24
};
function getObj(data) {
    console.log(data == person) // True where data is person and the expression value is the value to the right of =
}
getObj({ name, age } = person)
console.log(name) / / frogman
console.log(age) / / 24
Copy the code

In example above, getObj is called with a destruct assignment expression passed in. Since the JavaScript expression is the value on the right, the argument object in the function is the Person object, and the name and age variables are also reassigned.

When using destruct assignment, a variable is undefined if the specified variable name does not exist in the object. Here’s an example

let person = {
    name: "Frogman".age: 24
}
let { name, age, sex} = person;
console.log(name, age, sex) // Undefined
Copy the code

Example above, the deconstruction have sex variable assignment expression, but apparently object does not exist in the sex attribute, then the sex variable can be assigned to undefined.

When the specified property does not exist, we can set a default value, just like the default value for the function argument. Here’s an example

let person = {
    name: "Frogman".age: 24
}
let { name, age, sex = "male" } = person;
console.log(name, age, sex) // Frogman 24 male
Copy the code

In the example above, the default value for sex is set. The default value is only valid if the property is not present on the Person object or if the property is undefined. This is the same as the default value for functions. .

Deconstruct assignments to alias them

In the above code, we deconstruct expressions with the same variable and property name, so sometimes we don’t want to deconstruct the name of the property, what to do? Deconstruct expressions agree to support aliasing. Here’s an example

let person = {
    name: "Frogman".age: 24
}
let { name: userName, age: userAge } = person
console.log(userName) / / frogman
console.log(userAge) / / 24
Copy the code

In the example above, the deconstructed expression stored the name attribute in userName and the age attribute in userAge, so the name and age cannot be accessed because they are no longer variables.

Destructuring assignments with aliases also supports default arguments

Let person = {name: "frogman ", age: undefined} let {name: userName, age: undefined} UserAge = 24} = person console.log(userName) // Frogman console.log(userAge) // 24Copy the code

I won’t go into it here, but it’s the same as the default argument above.

Multiple layers of nested deconstruction of objects

Deconstruction assignments also support multiple levels of nesting, and the syntax is the same as for object literals, allowing for more detailed deconstruction. Here’s an example

let person = {
    name: "Frogman".age: 24.hobby: {
    	name: "Write code"}}let { hobby: { name: code = "code" } } = person
console.log(code) / / write code
Copy the code

In the example above, you can see that the syntax of the above layer of deconstruction is the same as that of normal deconstruction, only with a layer of {} curly braces nested inside. Above we have deconstructed the hobby property, then we go further and deconstruct the name property and give it a default value, and then we give it the individual name variable code.

Object destruct minefields need attention

One thing to be aware of when using multilevel nested deconstruction is that you may inadvertently create an invalid expression. Even if you deconstruct empty curly braces, the syntax is legal, and it does nothing and no errors. So let’s see.

Let person = {name: "frogman ", age: 24, hobby: {name:" code "}} let {name: {}} = personCopy the code

In the preceding statement, you can see that the deep deconstructing hobby property has a {} parenthesis to the right, but does not declare any variables. This statement is also reasonable and does not report errors. Official answer: This grammar may be obsolete in the future, but let’s just know not to write it like this.


An array of deconstruction

Array destructor syntax is similar to object destructor syntax, except that array destructor uses [] literal syntax. See the following example.

let colors = ["red"."blue"."green"]
let [ red, blue ] = colors
console.log(red, blue) // red blue
Copy the code

The biggest difference between array destructuring and object destructuring, object destructuring is unordered whereas array destructuring is ordered, so let’s look at an example.

let colors = ["red"."blue"."green"];
let [ blue ] = colors
console.log(blue) // red

let ObjColors = {
    red: "red".blue: "blue".green: "green"
}
let { blue } = objColors
console.log(blue) // blue
Copy the code

In the example above, we can see that the blue variable of the array destruct is red, so the array destruct is based on the position, a position for a value, not like object literals, there is a value in the object, we can get it directly, do not need to follow the order. And array deconstruction is sequential deconstruction.

If we just want to get the second value of the array, we can just ignore the first value and just write a placeholder. Here’s an example

let colors = ["red", "blue", "green"]
let [ , blue ] = colors
console.log(blue) // blue
Copy the code

In the example above, we only get the second value, so we break the array to the first value and write the blue variable, so we only get the second value.

As with object destructions, array destructions declared by var, let, or const must all be initialized, otherwise an error is thrown. As mentioned above when deconstructing the opposite side, remember that.

Array destruct default

The array destruct default is the same as the object destruct default, as long as there is no value in the array or the value is set to undefined then the default value is valid.

let person = ["Frogman".24]
let [ name, age, sex = "male" ] = person
console.log(name, age, sex) // Frogman 24 male
Copy the code

Multilevel nested deconstruction of arrays

Multilevel destructuring of arrays is similar to multilevel destructuring of objects, except that the syntax is different. Arrays are destructed in order using []. Let’s look at an example

let person = ["Frogman".24["Write code"."Liao sister"."Badminton"]]
let [ name, age, [firstHobby] ] = person
console.log(name, age, firstHobby) // Frogman 24 write code
Copy the code

In the example above, we can see that when we deconstruct multiple layers, we use the square brackets [] to extract the desired data layer by layer.

The syntax for array destructuring is similar to that for object destructuring, just pay attention to how array destructuring is used[]Object destructor{}, and their minefields are the same. I use deconstruction and then I have to initialize the value on the right, otherwise I get an error.

Mixed deconstruction

So with that said, that’s all about single object destructuring, so now we can do some hybrid destructuring, which involves using both data destructuring and object destructuring. Here’s an example

let person = {
    name: "Frogman".age: 24.sex: "male".hobby: ["Write code"."Liao sister"."Badminton"]}let { name, sex, hobby: [, , lastHobby] } = person
console.log(name, sex, lastHobby) // Male badminton
Copy the code

In example above, person is an object that defines personal information. And then when we go down to destructuring, we use object destructuring and array destructuring, and then we know that array destructuring can only be done by location, so we use an array placeholder to get the value of the last array.

So where is all this grammar used? In what kind of scenarios? Here’s a look at some of these syntax scenarios

Application scenarios

Object to deconstruct

Usually in Es5, if we want to do a profile presentation, we write a function and we pass an object, and in that function we have to declare and assign a bunch of variables, and those values are taken from that object that we pass in. Here’s an example

function informationFn(data) {
    let name = data.name;
    let age = data.age;
    let sex = data.sex;
    let email = data.email;
    let phone = typeofdata.phone ! ="undefined" ? data.phone : "No.";
}
let person = {
    name: "Frogman".age: 24.sex: "Male".email: "[email protected]".phone: undefined
}
informationFn(person)
Copy the code

In the example above, you can see that the code is fine, but there is too much code, resulting in code redundancy. Now let’s use Es6 syntax to implement the above function.

Function informationFn({name, age, sex, email, phone = "none"}) {console.log(name, age, sex, email, Phone)} let person = {name: "frogman ", age: 24, sex:" male ", Email: "[email protected]", phone: undefined} informationFn(person)Copy the code

In the example above, we use Es6 syntax objects to deconstruct and deconstruct the default values again, and you can see that the code is very concise.

Array deconstruction and assignment

In Es5, when we want to implement an exchange of values between two variables, we have to rely on the first variable to implement it.

let a = 1;
let b = 2;
let temp;
temp = a;
a = b;
b = temp;
console.log(a, b) // 2 1
Copy the code

In Es6, however, you don’t need to do this at all, so let’s see how to do that.

let a = 1;
let b = 2;
[ a, b ] = [b, a]
console.log(a, b)
Copy the code

In the example above, the expression on the right side of the destruct assignment is a temporary array that evaluates the right side of the array first, and then assigns the right side of the array to the preceding variable.

Thank you

Thank you in spite of your busy schedule to open this article, I hope you can be helpful, if there is a problem welcome to corrections.

If you think it’s ok, click “like”.

If you are interested, you can also add my personal VX to communicate with me