ES6 common questions


1. The difference between Es5 and ES6. Tell me what you know about ES6
Ecmascript5, or Es5, is the fifth revision of ECMAScript. The standardized ecmascript6, or ES6, was completed in 2009. It is the sixth revision of ECMAScript and was completed in 2015. Also known as es2015es6, it is an improvement after Es5. Compared with Es5, it is more concise and improves the development efficiency. Some new features of ES6:

1) Let declares variables and const declares constants, both of which have block level scope. Es5 does not have block level scope, and VAR has variable promotion. In let, the variables used must be declared
    2) The function definition in the arrow function ES6 no longer uses the keyword function (), but uses () = > to define
    3) Template string template string is an enhanced version of string. It is identified by back quotation marks (`). 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 loop the for... Of loop can traverse arrays, set and map structures, some array like objects, objects, and strings
    6) In the import and export ES6 standards, the JS native support module. 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 itself a constructor
    8) ... expansion operator can expand the values in the array or object; You can also collect multiple values as a variable
    9) Modifier @ decorator is a function that modifies the behavior of a class or even a method. Modifiers are essentially functions that execute at compile time
    10) Class class inheritance in ES6, the prototype chain is no longer used to implement inheritance like Es5, but the concept of class is introduced. 11) async and await use async / await, combined with promise, to process asynchronous processes by writing synchronous like code to improve the simplicity and readability of the code. Async is used to declare that a function is asynchronous, 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) Symbolsymbol 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 proxy uses proxy to listen to the operation of objects, and then can do some corresponding things

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 Template Strings in ES6? And realize the function of a class template string

Basic string formatting.
Embed expressions into strings for splicing.
Use ${} to define. In Es5, we use backslash () to do multi line string or string line by line splicing.
ES6 back quotation marks (` `) can solve the function of class template string
let name = 'web';
let age = 10;
Let STR = 'Hello, ${name} is ${age}'
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 is used for data reorganization and map is used for data storage: 
(1) Members cannot be duplicate
(2) Only key values without key names are similar to arrays
(3) It can be traversed. The methods include add, delete and has
(1) It is essentially a set of key value pairs, similar to a set
(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. 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. After the synchronous code in the macro task is executed, the async function will be executed, indicating that there may be asynchronous methods in the function, and await will be 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 states:
Two processes:
Padding - > fulfilled, padding - > rejected when pending is rejected, it will enter catch

10. What is the output below

const promise = new Promise((resolve, reject) => {

promise.then(() => {

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",    

13. In the following set structure, what is the printed size value

let s = newSet();

Answer: 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 values 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 (executor) {// the constructor contains an executor
      this.status = 'pending';// The default state is pending
      This.value = undefined // the successful value is undefined by default
      This.reason = undefined // the default value of failure is undefined
      //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;
        //Pass the resolve and reject functions to the executor executor
        reject(e);// If it fails, enter the catch
      //Onfuffilled is called if the status is successful
      if(this.status = 'resolve'){
      //Call onreject if the status fails
      if(this.status = 'reject'){

16. How to use set de duplication

let arr = [12,43,23,43,68,12];
let item = [ 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';