An article to learn ES6

1, The difference between es5 and es6. Tell me what you know about es6

ECMAScript5, or ES5, is the fifth revision of ECMAScript and was standardized in 2009

ECMAScript6, or ES6, is the sixth revision of ECMAScript and was completed in 2015, also known as ES2015

ES6 is an improvement after ES5. Compared with ES5, it is more concise and improves the development efficiency

Some new features in ES6:

(1) let declares variables and const declares constants, both of which have block level scopes
There is no block level scope in ES5, and var has variable promotion. In let, the variables used must be declared

(2) arrow function
The function definition in ES6 no longer uses the keyword function(), but uses () = > to define

(3) template string
The template string is an enhanced version of the string, which is identified by backquotes (`). It can be used as an ordinary string or to define a multi line string

(4) deconstruction assignment
ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern

(5) for of cycle
The for... of loop can traverse arrays, Set and Map structures, some array like objects, objects, and strings

6) import, export
In the ES6 standard, JS native supports modules. The JS code is divided into small blocks with different functions for modularization, and the codes with different functions are written in different files. Each module only needs to export the public interface part, and then it can be used in other places through module import

(7) set data structure
Set data structure, similar to array. All data are unique and have no duplicate values. It is a constructor itself

(8)... Expand operator
You can expand the values in an array or object; you can also collect multiple values as a variable

(9) modifier@
Decorator is a function used to modify the behavior of a class or even a method. A decorator is essentially a function executed at compile time

(10) class inheritance
In ES6, the prototype chain is no longer used to implement inheritance like in ES5, but the concept of Class is introduced

( 11)async,await
Using async/await and promise, you can write synchronous code to handle asynchronous processes and improve the simplicity and readability of the code
async is used to declare that a function is asynchronous, while await is used to wait for the execution of an asynchronous method to complete

( 12)promise
Promise is a solution for asynchronous programming, which is more reasonable and powerful than traditional solutions (callback functions and events)

( 13)Symbol
Symbol is a basic type. Symbol is generated by calling the symbol function, which receives an optional name parameter. The symbol returned by the function is unique

(14) Proxy
Use a Proxy to listen to the operation of an object, and then you can do something accordingly

2, The difference between var, let and const

var declared variables can be declared repeatedly, while let cannot be declared repeatedly

var is not limited to the block level, while let is limited to the block level

var will be mapped to window (a property will be attached), while let will not be mapped to window

var can access variables on the declaration, while let has temporary deadband. Accessing variables on the declaration will report an error

Value must be assigned after const declaration, otherwise an error will be reported

const defines an immutable quantity. If it is changed, an error will be reported

Like let, const does not map to window, supports block level scope, and accesses variables on the declaration will report an error

3, What should we pay attention to when using arrow functions?

(1) With the arrow function, this does not point to the window, but to the parent (the point is variable)

(2) arguments object cannot be used

(3) It cannot be used as a constructor, which means that the new command cannot be used, otherwise an error will be thrown

(4) You cannot use the yield command, so the arrow function cannot be used as a Generator function

4, What are the new features of the template string in ES6? And implement the function of a class template string

	Basic string formatting. Embed expressions in strings for splicing ${}To define
	stay ES5 When we pass the backslash()To do multi line string or string line by line splicing. ES6 backquote (``)Can be solved

Functions of class template string:

		let name = 'web';
        let age = 10;
        let str = 'Hello, ${name} already ${age}Years old'
        str = str.replace(/\$\{([^}]*)\}/g,function(){
            return eval(arguments[1]);
        })
        console.log(str);//Hello, I'm 10 years old   

5, What are the differences between Set and Map?

Application scenario Set For data reorganization, Map For data storage
Set:  
	(1)Members cannot be duplicate
	(2)Only key values without key names are similar to arrays
	(3)Can traverse, the method is add, delete,has
Map:
	(1)It is essentially a collection of key value pairs, similar to a collection
	(2)It can be traversed and converted with various data formats

6, How does ECMAScript 6 write class and why does class appear?

The class of ES6 can be regarded as a syntax sugar, and most of its functions can be achieved by ES5. The new class writing method only makes the writing method of object prototype clearer and more like the syntax of object-oriented programming

//Define class
class Point { 
  constructor(x,y) { 
      //Construction method
       this.x = x; //this keyword represents an instance object
       this.y = y; 
  }
  toString() {
       return '(' + this.x + ',' + this.y + ')'; 
  }
}

7, Whether the Promise constructor is executed synchronously or asynchronously, what about the then method?

The promise constructor is executed synchronously, and the then method is executed asynchronously

8, Differences among setTimeout, Promise and async / wait

The event loop is divided into macro task queue and micro task queue

The callback function of setTimeout is placed in the macro task queue and executed after the execution stack is cleared

The callback function in promise.then will be placed in the micro task queue of the corresponding macro task and executed after the synchronization code in the macro task is executed

async function indicates that there may be asynchronous methods in the function, and await is followed by an expression

When async method is executed, if await is encountered, the expression will be executed immediately, and then the code behind the expression will be placed in the micro task queue, leaving the execution stack for the synchronous code to execute first

9, promise has several states. When will it enter catch?

Three statuses: pending, fulfilled, and reject

Two processes: padding - > fully and padding - > rejected

When pending is rejected, it will enter catch

10, What is the output below

const promise = new Promise((resolve, reject) => {
    console.log(1);
    resolve();
    console.log(2);
})

promise.then(() => {
    console.log(3);
})

console.log(4); // 1 2 4 3 

Promise will be executed immediately after it is created, so it will output 1 and 2 first, and the code inside Promise.then() will be executed immediately at the end of the current event loop, so it will continue to output 4 and finally output 3

11, Structure assignment is used to exchange the values of two variables

let a = 1;let b = 2;
[a,b] = [b,a];

12, Design an object, the type of key name contains at least one symbol type, and traverse all keys

let name = Symbol('name');
 let product = {
    [name]:"Washing machine",    
    "price":799
  };
  Reflect.ownKeys(product);

13, In the following Set structure, what is the printed size value?

let s = new Set();
s.add([1]);
s.add([1]);console.log(s.size); // 2

The two arrays [1] do not have the same value. The arrays they define respectively correspond to different storage addresses in memory. Therefore, not the same value can be stored in the Set structure, so the size is 2

14, What is the difference between reject and catch in Promise?

reject is used to throw exceptions, and catch is used to handle exceptions

reject is the method of Promise, and catch is the method of Promise instance

After reject, it will enter the second callback in then. If there is no second callback written in then, it will enter catch

Network exceptions (such as network disconnection) will directly enter the catch instead of the second callback of then

15, Write a promise using class

//Create a Promise class
  class Promise{
    constructor(executer){//The constructor is an executor
      this.status = 'pending';//The default state is pending
      this.value = undefined//Successful values are undefined by default
      this.reason = undefined//The failed value is undefined by default
      //The status can be changed only when pending
      let resolveFn = value =>{
        //It is judged that only when waiting can resolve succeed
        if(this.status == pending){
          this.status = 'resolve';
          this.value = value;
        }
      }
      //Judge that reject fails only when waiting
      let rejectFn = reason =>{
        if(this.status == pending){
          this.status = 'reject';
          this.reason = reason;
        }
      }    
      try{
        //Pass the resolve and reject functions to the executor executor
        executer(resolve,reject);
      }catch(e){
        reject(e);//If it fails, enter the catch
      }
    }
    then(onFufilled,onReject){
      //Onfuffilled is called if the status is successful
      if(this.status = 'resolve'){
        onFufilled(this.value);
      }
      //Call onReject if the status fails
      if(this.status = 'reject'){
        onReject(this.reason);
      }
    }
  } 

16, How to use Set de duplication

let arr = [12,43,23,43,68,12];
let item = [...new Set(arr)];
console.log(item);//[12, 43, 23, 68]

17, Change the following for loop to the form of for of

let arr = [11,22,33,44,55];
let sum = 0;
for(let i=0;i<arr.length;i++){
    sum += arr[i];
}


let arr = [11,22,33,44,55];
let sum = 0;
for(value of arr){
    sum += value;
}

18, Understand async/await and its advantages over Generator

async await is used to solve asynchronous. async function is the syntax sugar of Generator function

Use the keyword async to represent it, and use await to represent asynchrony inside the function

The async function returns a Promise object. You can use the then method to add a callback function

When the function is executed, once await is encountered, it will return first, wait until the asynchronous operation is completed, and then execute the following statements in the function body

Advantages of async over Generator:

(1) Built in actuator. The execution of the Generator function must rely on the executor, while the Aysnc function has its own executor, and the calling method is the same as that of ordinary functions

(2) Better semantics. async and await are more semantic than * and yield

(3) Wider applicability. The yield command can only be followed by the Thunk function or Promise object, and the await of the async function can be followed by Promise or the value of the original type

(4) The return value is Promise. The Promise object returned by the async function is more convenient than the Iterator object returned by the Generator function. You can call it directly with the then() method

19, Differences among forEach, for in and for of

forEach is more used to traverse arrays

for in is commonly used to traverse objects or json

for of array objects can be traversed. Traversing objects requires and Object.keys()

for in circulates the key, and for of circulates the value

20, Let's talk about the import and export module of es6

Import through import keyword

// Import only one
import {sum} from "./example.js"

// Import multiple
import {sum,multiply,time} from "./exportExample.js"

// Import an entire module
import * as example from "./exportExample.js"

Export via export keyword

//You can put export before any variable, function, or class declaration
export var firstName = 'Michael';
export var lastName = 'Jackson';
export var year = 1958;

//You can also use braces to specify a set of variables to output
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
export {firstName, lastName, year};

//When using export default, the corresponding import statement does not need braces
let bosh = function crs(){}
export default bosh;
import crc from 'crc';

//When export default is not used, the corresponding import statement needs to use braces
let bosh = function crs(){}
export bosh;
import {crc} from 'crc';

Tags: Javascript Front-end ECMAScript

Posted on Tue, 23 Nov 2021 01:58:13 -0500 by J4B