ES6+ (front-end interview questions integration)

ES6+ (front-end interview questions integration)

Talk about the difference between let and var and const

let is a new command for declaring variables for ES6. It is similar to var, but with the following differences:

  • The let command does not have variable promotion, if used before let, it will cause an error
  • The essence of let's temporary dead zone is actually the nature of block-level scopes that must be "declared before use". The reason for let's temporary dead zone is that var promotes variables, but let does not.
  • The global variables declared by let, const and class are not attributes of the global object
  • const can be shared among multiple modules
  • The variable declared by const is similar to the variable declared by let. The difference is that the variable declared by const can only be assigned at the time of declaration and cannot be modified at will, otherwise it will cause SyntaxError (syntax error)
  • const only guarantees that the address pointed to by the variable name remains unchanged, and does not guarantee that the data at that address remains unchanged

Talk about the characteristics of arrow functions

  • Arrow functions do not belong to ordinary functions, so there is no independent context.
  • The this object in the body of the arrow function is the object where it is defined, not the object where it is used.
  • Since the arrow function does not have its own this, the three methods call, apply, and bind in the function object cannot "overwrite" the this value in the arrow function.
  • Arrow functions do not have the hidden arguments object of the original (traditional) function.
  • Arrow functions cannot be used as generators. Using yield will cause errors.

Do not use arrow functions to define in the following scenarios:

1. Define object methods, define prototype methods, define constructors, and define event callback functions.

2. There is not only this but also arguments, super in the arrow function

Understanding of Symbol, Map and Set

Symbol is a special and immutable data type, which can be used as an identifier for object properties. Even if the symbol is instantiated with the same parameters, the symbol instances obtained will not be equal

the let _symbol1 = the Symbol ( 'Test' ); the let _symbol2 = the Symbol ( 'Test' ); Console .log (_symbol1 == _symbol2); //to false copy the code

The Map object stores key-value pairs, a bit similar to Object, but the key of Object can only be a string or Symbols, and Map can be any value

let myMap = new Map () let str1 = 'dog' let str2 = 'cat' myMap.set(str1, ' ' ) myMap.set(str2, ' ' ) console .log(myMap) //{0: {"dog" => " "}1: {"cat" => " "}} console .log(myMap. get(str1)) //Wang copy the code

The Set object allows you to store any type of unique value (array deduplication), a bit similar to Array, the elements in Set will only appear once

let mySet = new Set () mySet.add( 'hello' ) mySet.add( '1' ) mySet.add( '2' ) mySet.add ( '2' ) Console .log (MySet) //{0: "Hello",. 1: ". 1", 2: "2"} copy the code

How to monitor array changes using ES6 (proxy monitors reading and writing)

let list = [ 1 , 2 , 3 ] //proxy let _proxy = new Proxy (list, { set : function ( target, prop, val, rec ) { console .log( 'write' ) target[prop] = val return true }, get : function ( target, prop ) { console .log( 'Read' ) return target[prop] } }) _proxy[ 0 ] = 4 //write to console .log(_proxy[ 1 ]) //read copy code

What are the ways to handle asynchrony in JS

Callback function: A callback is a function that is passed as a parameter to another function, and then executed after that function is executed

Advantages: simple, convenient, practical and easy to understand.
Disadvantages: when the logic is complex, callback function hell will occur, the coupling is high, and the process will be very chaotic

//callback let cb = ( props ) => { console .log(props) //2 } let init = ( props ) => { //Asynchronous operation setTimeout ( () => { cb(props) //Asynchronous parameter transfer ), 1000 ) } the init ( 2 ) Console .log ( . 1 ) //. 1 duplicated code

Event publish/subscribe: using event-driven mode, the execution of tasks depends on whether a certain event occurs

Advantages: The event monitoring method realizes the decoupling of the code relative to the callback, which is very friendly to modular development.
Disadvantages: publish/subscribe events are required for each task execution

//Event publish/subscribe let cb = ( event ) => { console .log(event.props) //2 } let init = ( props ) => { //Asynchronous operation setTimeout ( () => { let event = new Event( 'myEvent' ) event.props = props //Pass the parameters asynchronously document .dispatchEvent(event) }, 1000 ) } the init ( 2 ) Console .log ( . 1 ) //. 1 Document .addEventListener ( 'myEvent' , CB) copy the code

Promise: Promise is asynchronous programming, which expresses asynchronous operations in a synchronous manner to avoid the generation of callback hell

Advantages: avoid callback hell, chain calls, clear function ideas, and stronger logic than the first two.
Disadvantages: poor understanding, asynchronous operations are inside the promise constructor

//ES6 Promise let init = ( props ) => { return new Promise ( ( resolve, reject ) => { //Asynchronous operation setTimeout ( () => { resolve(props) }, 1000 ) }) } init( 2 ).then( ( res ) => { console .log(res) //2 }) Console .log ( . 1 ) //. 1 duplicated code

Generator: Generator (generator) is a new data type introduced into Python by the ES6 standard

Advantages: the then canceled chain call is very similar to the publish/subscribe model, which is intuitive for understanding synchronous operations.
Disadvantages: multiple asynchronous functions are not intuitive enough. The original function needs to maintain the yield of the external function through next

//ES6 Generator const fn = init( 2 ) let cb = ( props ) => { console .log(props) //2 } function * init ( props ) { //Asynchronous operation yield setTimeout ( () => { }, 500 ) yield setTimeout ( () => { }, 500 ) cb(props) } Console .log ( . 1 ) //. 1 duplicated code


The async function is the syntactic sugar of the generator function. The async keyword is added before the function (function keyword), and the function waits for asynchronous execution through await

Advantages: The synchronization process is clear and concise, asynchronous operations can return promise objects, and subsequent operations are more convenient.
Disadvantages: JS's executor function is weaker than other co modules

//ES6+ async/await let cb = ( props ) => { console .log(props) //2 } let cb2 = ( props ) => { return new Promise ( ( resolve, reject ) => { setTimeout ( () => { resolve(props) }, 1000 ) }) } async function init ( props ) { //Asynchronous operation let num2 = await cb2(props) cb(num2) } the init ( 2 ) Console .log ( . 1 ) //. 1 duplicated code

What is the difference between the class keyword and function in ES6

  • In the constructor defined by function, its prototype.constructor attribute points to the constructor itself. In the class defined by class, the constructor is actually defined on the prototype attribute.
  • If the function is defined repeatedly, it will overwrite the previously defined method, and the class repeated definition will report an error
  • The methods defined in the class cannot be enumerated by Object.keys (Point.prototype), and the function constructor prototype method can be enumerated by Object.keys (Point.prototype)
  • The class does not have variable promotion, that is, the class must be defined first, and then used, and after the function is defined, it will be promoted to the top of the current scope
  • The class defined by class has no private methods and private properties, function can realize private methods and properties through closures

What array methods are new in ES6

find(): returns the first element in the array that meets the condition (if there is any), if not, returns undefined
findIndex(): returns the index of the first element in the array that meets the condition (if any), If not, it returns -1
keys(): returns an array index iterator
values(): returns an array iterator object that contains the value of each index in the array
entries(): returns an array iterator object This object contains key-value pairs for each index in the array

The difference between for in and for of

for in is suitable for traversing objects, for of can be used for traversing arrays, array-like objects, argument, string, Map and Set

There are the following problems when for in traverses the array:

  • The index index is a string type number, so geometric operations cannot be performed directly
  • The traversal order may not be in accordance with the internal order of the actual array
  • Using for in will traverse all enumerable properties of the array, including prototypes, methods and properties on the prototype

So for in is not suitable for traversing arrays, but for traversing objects

And when for of traverses the array :

Only traverse the elements in the array, not including the prototype attribute method and index name of the array

The difference between require/exports in CommonJS and import/export in ES6

  • The output of the CommonJS module is a copy of the value, and the output of the ES6 module is the reference of the value
  • CommonJS module is loaded at runtime, ES6 module is the output interface at compile time, ES6 can complete module loading at compile time, and the efficiency is higher than the loading method of CommonJS module
  • The output of the CommonJS module is a copy of the value, that is, once a value is output, changes within the module will not affect the value. The operating mechanism of the Es6 module is different from that of CommonJS. When the JS engine analyzes the script statically, it will generate a read-only reference when it encounters the module loading command import. When the script is actually executed, the value is obtained in the loaded module based on the reference. ES6 modules are dynamically referenced and will not cache values. The variables in the module are bound to the module where they are located.
  • Require/exports is implemented in Node by CommonJS, and import/export is a module of ES6
  • Require/exports is a synchronous import, because it is used on the server side, the files are all local, and the synchronous import has little effect even if the main thread is stuck. The ES6 module is imported asynchronously, because it is used in the browser, and the file needs to be downloaded. If the import is also used, the rendering will be greatly affected.
  • The design idea of ES6 module is to be as static as possible, so that the dependencies of the module, as well as the input and output variables can be determined when compiling, and the ES6 module will be compiled into require/exports for execution
  • The export command is used to specify the external interface of the module, and the import command is used to enter the functions provided by other modules

Try to implement Promise

The difference between and "==", "==="

"==" will perform type conversion during comparison

"===" No implicit type conversion during comparison specially handles NaN, -0, and +0 on the basis of the third-equal sign, to ensure that -0 and +0 are no longer the same, but,NaN) will return true

Why does Class appear in ES6

The function of Class can actually be realized in ES5, which can be regarded as the syntactic sugar of ES6. Its function is to make JS syntax clear and more like object-oriented syntax.

Basic writing

class MyEvent extends EventTarget {//inherit EventTarget constructor ( e ) { super (e)//the constructor of the parent class this .consoleThis()//execute the function } consoleThis () { console .log( this ) } } the let myEvent = new new the MyEvent ( Document ) //the EventTarget  duplicated code

What are the attribute abbreviations and attribute name expressions of ES6 syntactic sugar objects?

Property shorthand: the literal of the object can be directly written into the variable and function with the same name

let name = ' ' function showName () { console .log( this .name) } let person = { name, showName } console .log( //Xiaoming person.showName() //Xiaoming copy code

Attribute name expression abbreviation: ES6 allows expressions to be placed in square brackets as the attribute name of the object

let num = 0 let obj = { "1" : 'a' , "2" : 'b' , "3" : 'c' } Console .log (obj [NUM ++]) //A Console .log (obj [NUM ++]) //B Console .log (obj [NUM ++]) //C duplicated code

Talking about the Understanding of Deconstruction Assignment

Destructuring assignment is an extension of the assignment operator, which is a pattern matching for arrays or objects, and then assigning values to the variables in it

//array let [a, b, c] = [ 1 , 2 , 3 ]; console .log(a, b, c) //1,2,3 //object let { d, e, f } = { d : 4 , e : 5 }; Console .log (D, E, F) //4,5, undefined copy the code

How to merge multiple objects and copy objects using ES6

The new (...) extended operator for objects in ES6 is used to retrieve all traversable properties of the parameter object and copy to the current object

ES6 new object copy method: Object.assign(target, source1, source2, source3, ), copy all enumerable properties of the source object to the target object, that is, source1, source2, source3... ...Copy to target


let name = { name : 'Xiao Ming' } let age = { age : 20 } let hobby = { hobby : 'music' } let person = { //expand operator, ...age, ...hobby } console .log(person) //age: 20,hobby: "music",name: " " Object .assign (Person, name, Age, Hobby) //copy objects Console .log (Person) //Age: 20 is, Hobby: "Music", name: "Bob" copy the code


let list = [ 1 , 2 , 3 , 4 , 5 ] let list2 = [...list] //extension operator Object .assign(list2, list) //object copy let index = 0 do { list[index] += 10 } while (index++ <list.length- 1 ) console .log(list, list2) //[11, 12, 13, 14, 15] [1, 2, 3, 4, 5] Copy code

How to control the read and write of attributes in a class


class Animal { constructor () { this ._dog = 'Little Black' this ._cat = 'Little Yellow' } set cat ( val ) { //just write this ._cat = val } get dog () { //read only return this ._dog } } let animal = new Animal() = 'Little White' = 'Little Grey' console .log(, //Little Black undefined console .log(animal._dog, animal._cat) //Little Black Gray copy code

Object.defineProperty () modify the object read-only

class Animal { constructor () { this .dog = 'Little White' } } let animal = new Animal() Object .defineProperty(animal, 'dog' , { writable : false , //writable, false is read-only }); = ' Xiao Hei ' console .log( //Xiao Bai copy the code