ES6 GAP1: let and const, deconstruct assignment, expand operator

ES6 GAP-up series 2: Arrow functions, template strings

Let and const

Why introduce let and const?

Var declares variables.

Before ES6, variables could only be declared using var. Using var had the following problems:

Allow duplicate variable declarations: results in data being overwritten

Variable promotion: Weird data access, closure issues

Global variables mounted to global objects: Global object member contamination problem

// Variable promotion: weird data access
if (Math.random() < 0.5) {
    var a = "abc";
    console.log(a);
}
else {
    console.log(a);
}
console.log(a);ABC > / / < 0.5 = 0.5 undefined

// Variable promotion: closure problem
var div = document.getElementById("divButtons")

for (var i = 1; i <= 10; i++) {
    var btn = document.createElement("button");
    btn.innerHTML = "Button" + i;
    div.appendChild(btn);
    btn.onclick = function () {
        console.log(i); / / output 11}}// Global variables mounted to global objects: global object member contamination problem
var abc = "123";
console.log(window.abc);
Copy the code

To address these issues, ES6 adds lets and const

Let and const properties?

Block-level scope: when a brace is encountered during code execution, a block-level scope is created, the brace ends, and the block-level scope is destroyed

Variable assignment: A variable declared by let can be reassigned within the same scope. Const must be assigned at the same time it is declared, and its value cannot be modified. Declared variables cannot be accessed outside the scope

Variable promotion: Neither let nor const can be promoted; therefore, they cannot be used before they are declared. In the underlying implementation, the variables declared by the let are actually promoted. However, when promoted, they are placed in a “temporary dead zone”. If the variable is in a temporary dead zone, an error is reported: “Cannot access ‘a’ before Initialization”. When the code runs into the declaration of the variable, it is removed from the temporary dead zone.

Closure problem handling: Loop variables declared in let are treated in a special way, opening a new block-level scope each time they enter the body of the loop and binding the loop variable to that scope (each time a brand new loop variable is used). Loop variables declared in the loop using let are destroyed at the end of the loop.

MDN document link: let const

Deconstruction assignment

What is deconstruction assignment and what does it do

Destruct assignment is a syntactic sugar provided by ES6 that allows you to take properties/values out of objects/arrays and assign them to other variables.

// Get the value of the object
const obj = {a:1.b:2};
let a = obj.a;
let b = obj.b;
console.log(obj.a,obj.b);
// Get the value of the array
const arr =[1.2];
let num1 = arr[0];
let num2 = arr[1];
Copy the code

The following code results in the same result as the above, except that the following one uses deconstructed assignment

// Get the value of the object
const {a,b}={a:1.b:2};
// Get the value of the array
const [num1,num2]=[1.2];
Copy the code

Destruct assignment differs between object and array destruct assignment. Objects are evaluated by property, while arrays are evaluated by index

It also provides syntactic sugar for default parameters and variable renaming for destructuring assignments

// Default parameters
let {a,b=5,c=1} = {a:1.b:2};
let [num1,num2=10,num3=1] = [1.2];
// The variable has the same name
let {a:a1,b}={a:1.b:2};
console.log(a1)/ / 1
console.log(a)Uncaught ReferenceError: A is not defined
Copy the code

By deconstructing the assignment, the value exchange of two variables can be realized quickly

let a=11,b=22;
[b,a]=[a,b];
Copy the code

How to Deconstruct assignment (How to implement it)

Inherent in it is the Iterator interface for iterable objects, which is assigned by obtaining corresponding values sequentially through the Iterator (for of)

MDN document link: Destruct assignment

Expansion operator

How to use the expansion operator lazy

The expansion operator can expand an array expression or string syntactically during a function call/array construction. You can also construct literal objects by expanding the object expression key-value

// String expansion
let str='bar';
const strArr = [...str]; // ["b", "a", "r"]


// Array expansion
const arr1 = [1.2.3];
const arr2 = [...arr1,4]; / / [1, 2, 3, 4]

// Expand the object
const obj1 = {a:1.b:2};
constobj2 = {... obj1,c:3}; // {a: 1, b: 2, c: 3}


Copy the code

Lazy operation: use expansion operators to replace some API functions and reduce API memory

/ / replace arr. Concat ()
const arr3 = [...arr1,...arr2]; // const arr3 = arr1.concat(arr2);

/ / replace arr. Push ()
const arr3 = [1.2.3.4]; arr3.push(... arr);// equivalent arr3 = [1,2,3,4...arr]

/ / replace arr. Unshift ()
const arr3 = [1.2.3.4]; arr3.unshift(... arr)// equivalent arr3 = [...arr,1,2,3,4]

// Replace object.assign () same
constobj3 = {... obj1,... obj2}// Const obj3 = object. assign({},obj1,obj2)
Copy the code

In addition to expanding strings, arrays, and objects, the expansion operator can also reassemble remaining arguments into arrays and objects

// Use (remaining arguments) when calling a function
let a1=1,a2=2,a3=3;
function sum(a1,... arr){
    console.log(arr)/ / [2, 3]
    return a1*2 + arr.reduce((a,b) = >a+b) 
}
sum(a1,a2,a3) / / 7

// Array collection
[1. arr] = [1.2.3.4]  / / arr = [4] 2
// Object collection
{ a : 1. obj } = {a:1.b:2} //obj={b:2}
Copy the code

MDN documentation: Expand operator remaining parameters