What is ES6? What is the difference between ES5, ES6 and ES2015?

ES6 is a new generation of JS language standard. It has optimized and upgraded some JS languages and standardized the usage standards of JS, making the use of JS more standardized, more elegant and more suitable for the development of large applications.

S2015 refers to the new generation of JS language standards released in 2015. ES6 generally refers to the next generation of JS language standards, including ES2015, ES2016, ES2017, ES2018, etc. Currently, ES2015 is equivalent to ES6 by default in most scenarios. ES5 generally refers to the previous generation of language standards. ES2015 is the time demarcation between ES5 and ES6.

Let and const commands

1. Basic usage

ES6 added the let command to declare variables, similar to var, but only valid within the let code block.

for (let i = 0; i < 10; i++) {
  // ...
}

console.log(i);
// ReferenceError: i is not defined
Copy the code

In the loop above, I is only valid in the for loop

{
  let a = 10;
  var b = 1;
}

a // ReferenceError: a is not defined.
b // 1
Copy the code

The code a above is valid only in the block it is in

There is no variable promotion

Var variables can be promoted, that is, they can be used before the declaration, and the value is undefined. Let must be used after the variable declaration or an error will be reported.

// var case console.log(foo); Var foo = 2; //letThe situation of the console. The log (bar); / / error ReferenceErrorlet bar = 2;
Copy the code

Temporary dead zone

As long as a let command exists in a block-level scope, its declared variables are bound to the region, unaffected by external influences.

var tmp = 123;

if (true) {
  tmp = 'abc'; // ReferenceError
  let tmp;
}
Copy the code

ES6 explicitly states that this variable is not available until let is declared, known as a temporary dead zone.

Duplicate declarations of variables are not allowed

Let does not allow the same variable to be declared twice in the same scope.

/ / an errorfunction func() {
  leta = 10; var a = 1; } // Basic usage errorfunction func() {
  let a = 10;
  let a = 1;
}
Copy the code

2. Block level scope

Block-level scope functions without block-level scope, which leads to a lot of irrational scenarios

  • Inner variables may override outer variables
  • Loop variables used to count may leak out as global variables.

3. The const command

The value of a constant cannot be changed once it is declared, and it must be initialized immediately after it is declared or an error will be reported.

const foo;
// SyntaxError: Missing initializer in const declaration
Copy the code

Const is scoped in the same way as the let command and is only valid in the block-level scope in which it is declared. Used to ensure that declared variables are not changed.

Var,function, let, const, import, class

3. Deconstructive assignment of variables.

The left and right sides must have the same structure; Right legal; Declaration and assignment cannot be separated (must be done in one sentence)

1. Array deconstruction assignment

Basic usage

Previously, assigning a variable could only specify a value directly

let a = 1;
let b = 2;
let c = 3;
Copy the code

ES6 let [a, B, C] = [1, 2, 3];

let[foo, [[bar], baz]] = [1, [[2,3]]; Foo // 1 bar // 2,3 baz // 3let [ , , third] = ["foo"."bar"."baz"];
third // "baz"

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

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
Copy the code

If parsing fails, the value of the variable is undefined

let [foo] = [];
let [bar, foo] = [1];
Copy the code

In both cases, foo is undefined;

The default value

Destruct assignment allows you to specify default values.

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
Copy the code

2. Deconstructed assignment of objects

Variables must have the same name as attributes to be successfully assigned

let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined
Copy the code

3. Function extension

Default values for function arguments (important)

Es6 allows you to set default values for parameters directly, defined directly after the parameters.

function log(x, y = 'World') {
  console.log(x, y);
}

log('Hello') // Hello World
log('Hello'.'China') // Hello China
log('Hello'.' ') // Hello
Copy the code

The length property of the function returns the number of arguments that do not have a default value specified

(function (a) {}).length // 1
(function (a = 5) {}).length // 0
(function (a, b, c = 5) {}).length // 2
Copy the code

Rest parameters :(form… The rest argument is an array of variables. The rest argument is an array of variables. The rest parameter cannot be followed by any other parameter.

functionadd(... values) {let sum = 0;

  for (var val of values) {
    sum += val;
  }

  return sum;
}

add(2, 5, 3) // 10
Copy the code

Extension operator :(form…) You can split an array into several parameters.

console.log(... [1, 2, 3]) // 1 2 3 console.log(1, ... [2, 3, 4], 5) // 1 2 3 4 5 [...document.querySelectorAll('div')]
// [<div>, <div>, <div>]
Copy the code

Basic usage of arrow function (emphasis)

Basic usage

It is possible to define functions using arrows, if only one argument parenthesis is omitted, and if there is a return, {} can be omitted

var f = v => v;
Copy the code

Is equivalent to

var f = function(v) {
  return v;
};
Copy the code

If you don’t need or need more than one argument, you can represent the argument part with a function

var f = () => 5; // the same thing as var f =function () { return5}; var sum = (num1, num2) => num1 + num2; Var sum = var sum =function(num1, num2) {
  return num1 + num2;
};
Copy the code

Points to note when using arrow functions

  • The this object inside the function is the object at which it is defined, not used.
  • Do not use the new command as a constructor.
  • Instead of using arguments objects, you can use rest arguments instead
  • Yield cannot be used, so arrow functions cannot be used as Generator functions.

Note that in the arrow function, the pointer of this is fixed, and it does not have its own this inside, which leads to the fact that this always points to this in the upper layer. If the upper layer is still the arrow function, it will continue pointing up until it points to a function with its own this as its own this.

Extension of arrays

  • The map mapping
letArr =,5,8 [12];let result =arr.map((item)=>{
    return item *2;
})

letScore =,85,99,25 [19];let result=score.map(item=>item>=60?'pass':'Fail');

Copy the code
  • A) reduce B) sum C) average D) sum
letArr =,46,33,56 [12]; // Calculate the sum, temp represents the intermediate result, item traversal group, index, number of cycleslet num=arr.reduce(function(temp,item,index){
    return temp+item;
})
Copy the code
  • Filter, keep some, leave some
// Leave a multiple of 3, leave a returntruePart of theletArr =,5,6,75,46 [12];let result=arr.filter(item=>{
    if(item%3==0)
        return false;
    else return true;
})
Copy the code
  • ForEach loop iterates

4. Object extension

  • You can declare properties or methods directly in variable form (traditional key-value pair form)
let es5Fun = {
    method: function(){}
}; 
let es6Fun = {
    method(){}
}
Copy the code

5. What is Symbol? What does it do?

Symbol is the seventh primitive data type introduced in ES6. All values generated by Symbol() are unique and can accept a string as an argument. Var s1=Symbol(); Var s2=Symbol(“foo”), which can be an attribute name and is not a private attribute

let a={};
let name=Symbol();
a[name]='oll';
Copy the code

6. Promise

Complete asynchronous request: multiple tasks at the same time, code more complex form:

let p=new Promise(function(resolve,reject){//resolve //reject $.ajax({url:'arr.text',
        dataType:'json', success(arr){ resolve(arr); } err0r(err){reject(err)}})}) // The promise object is discardedthenThe function starts executing,thenThe first argument to the resolve function is reject, and the second argument to the reject function is reject.function(){
    alert('It worked')},function(){
    alert('Failed')})Copy the code

Focus on promise.all method

function createPromise(url){
    return new Promise(function(reslove,reject){
        $ajax({
            url,
            dataType:'json', success(arr){resolve(arr)}, error(err){reject(err)}})})}function(arr){ console.log(arr); // The content is passed in Ajax, but the content is placed in arRlet[res1,res2]=arr; // The result can be decomposed by destructuring the assignment.function(){// a failure will return a failure result})Copy the code

Code optimization

Promise.all([
$ajax({}),
$ajax({})
]).then(function(results){
    let[arr1,arr2]=result; 
},function(){// failed})Copy the code

7. What are async and await doing

To solve the async problem, async returns a Promise object, await is waiting for an async function to complete, because async function returns a Promise object, await must appear inside async function, Should not be used alone if the await function waits for a promise object, await blocks subsequent code

For example:

// We still use itsetTimeout to simulate asynchronous requestsfunction sleep(second, param) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(param);
        }, second);
    })
}

async function test() {
    let result1 = await sleep(2000, 'req01');
    let result2 = await sleep(1000, 'req02' + result1);
    let result3 = await sleep(500, 'req03' + result2);
    console.log(`
        ${result3}
        ${result2}
        ${result1}
    `);
}

test(a); //req03req02req01 //req02req01 //req01Copy the code

8.Proxy

  • What is a Proxy? Is a constructor provided in ES6 that acts more like an interceptor and uses our defined interceptor methods first to access assignments.

  • Why Proxy()? Proxy objects do not want to be accessed directly. When the propped object is not capable, find someone to do it for him and add new functions

  • What is the use of Proxy? The Proxy constructor accepts two parameters, new Proxy(target, Hander), where the target parameter refers to the target object (the object being propped), an object, and the properties are the behavior of various basic methods to control and modify target.

For example, if a user has no profile picture set, the default profile picture is returned

const user={name="cz"};
const userProxy=new Proxy(user,{
    get:(obj,prop)=>{
        if(prop==='avatar') {if(! obj.prop){return 'https://... '}}returnobj[prop]; }})Copy the code

9. The Generator function

  • What is Generator()?Execution to the middle can stop, cooperateyieldFunction USES
  • Function: Can realize asynchronous with logic
// * * * * * * * * *function *show(){
    alert('a');
    
    yield;//控制在哪里停
    
    alert('b'); } // It is also special to useletgenodj=show(); genobj.next(); Genobj.next (); // Start execution, print a, stop at yield; // Print out bCopy the code

Yield can either pass an argument or return it.

function *show(){
    alert('a');
    
    leta=yield; // control where to stop, can have a return value, at this point a value of 5 alert('b'); } // It is also special to useletgenodj=show(); genobj.next(12); // genobj.next(5); //Copy the code
runner(function* () {let data1=$.ajax({url:,dataType});
    let data2=$.ajax({url:,dataType});
    let data3=$.ajax({url:,dataType});
})
Copy the code