(1) Const and let and var

1. The difference between the three

  • 1. Variable improvement
  1. Var declarations are considered to be declared at the top of the function wherever they are declared
  2. Let and const declarations do not promote
  • 2. Scope
  1. Var is the scope of the function, which is used inside the function, but {} is also promoted
  2. Let and const are block-level scopes, which form a scope in {}
  • 3. Repeat statements
  1. Var can be defined repeatedly
  2. Let and const must not be repeated, otherwise an error will be reported
  • 4. Const constants cannot be modified
  1. A variable declared as const is considered constant, meaning that its value cannot be changed once it has been set;
  • 5. If const is an object, the value contained in the object can be modified. In the abstract, the address to which the object points remains the same:
const student = { name: 'cc' } = 'yy'; Student = {name:'yy'}; / / an errorCopy the code

2. Temporary dead zone

var tmp = 123;
if (true) {
  tmp = 'abc'; // ReferenceError
  let tmp;
Copy the code
  • In the above code, there are global variablestmp, but in the block-level scopeletAnother local variable is declaredtmpCauses the latter to bind to this block-level scope, so inletBefore you declare a variable, yeahtmpThe assignment will report an error.

A few points to note:

In the following case, use the following reactoid in the following case: # let keyword declared variables do not have the reactoid promotion feature
The # let and const declarations are valid only in the closest block (within curly braces)
# When using const declarations, use capital variables such as CAPITAL_CASING
# const must be assigned when declared
Copy the code

3. Suggest

In daily development, my advice is to fully embrace the let/const, general use variable declarations let keyword, and when declare some configuration items (similar to the interface address, NPM depend on package, pager once the default number of pages and some other statement after he won’t change the variables) can use const, when other developers to explicitly tell the project, This variable cannot be changed (use all uppercase for const declarations, and underline between words). It is also recommended that you be aware of the flaws of the var keyword (promoting variables, polluting global variables, etc.) so that you can use the new syntax better


(1) Arrow Functions

  • In ES6, an arrow function is a shorthand for a function, enclosing the arguments in parentheses, followed by a =>, followed by the body of the function;

1. Arrow functions have the following differences for functions created using the function keyword:

  1. Arrow function does not have arguments (suggest better syntax, remaining operator instead)
  2. Arrow functions have no Prototype property and cannot be used as constructors (cannot be called with the new keyword)
  3. The arrow function does not have its own this, its this is lexical, it refers to the context this, When you write this line of code, the “this” function is bound to the “this” context in which the arrow is executed. (This does not mean that the “this” function is completely static, because the “this” context is still dynamic and can be modified using call,apply, or bind. Of this,

2. The three most intuitive features of the arrow function

# You do not need the function keyword to create a function
# Omit the return keyword
# inherit the this keyword from the current context
Copy the code
  • Details: When your function has only one argument, you can omit the parentheses. You can omit {} and return if your function returns only one expression;

Rules of 3.

  1. Arrow functions that use block statements do not automatically return values. You need to use the return statement to return the desired values.
  2. They cannot be used as constructors; that is, they cannot instantiate an object with the new keyword, otherwise an error will be thrown.
  3. You cannot use the Arguments object, nor can you access passed arguments through the Arguments object, which does not exist in the function body. If so, use the REST parameter instead.
  4. You cannot use the yield command, so arrow functions cannot be used as Generator functions.
  5. Var getTempItem = id = > ({id: id,});

(2) Default values for function parameters

// Before ES6, when no argument is passed, text ='default';function printText(text) {
    text = text || 'default'; console.log(text); } / / ES6;function printText(text = 'default') {
printText('hello'); // hello
printText(); // defaultCopy the code

A. Promise B. Promise C. Promise D. Promise

As a new concept introduced in ES6, Promise has changed JS asynchronous programming. Most asynchronous requests in modern front-end are implemented using Promise. Fetch, a Web API, is also based on Promise. What does Promise do to ameliorate these weaknesses

Disadvantages of callback functions

  1. Multiple nesting, resulting in callback hell
  2. Code jumping is not the way humans are used to thinking
  3. Trust issues, you can’t trust your callback to a third party library, because you don’t know exactly how the third party library will perform the callback (multiple times)
  4. Third-party libraries may not provide error handling
  5. It is not clear if all callbacks are called asynchronously (you can call Ajax synchronously and block the entire thread until you receive a response, which can lead to suspended animation and is highly recommended)


A Promise is a constructor that uses the new keyword to create an instance of a Promise. How can a Promise solve these problems

  1. It is not clear if all callbacks are called asynchronously (you can call Ajax synchronously and block the entire thread until you receive a response, which can lead to suspended animation and is highly recommended)
  • Promise is designed to ensure that all response callbacks are called asynchronously and do not block code execution. Promise queues the then callback to a MicroTask and ensures that these callbacks are not executed until the synchronization task has completed. This part is also the knowledge point of the event cycle, interested friends can in-depth research


  • In daily development, it is recommended to fully embrace the new Promise syntax. In fact, today’s asynchronous programming is basically using promises
  • It is recommended to further optimize the writing of promises using ES7’s async/await function. Async functions always return a Promise, and await implements a “wait” function. Async /await is considered the ultimate solution for asynchronous programming, that is, to write asynchronous code synchronously. And can be more elegant implementation of asynchronous code sequence execution and asynchronous error in the occurrence of error to provide more accurate error information


(1) String template

  • When concatenating strings, try to use template strings instead:
// bad
const foo = 'this is a' + example;

// good
const foo = `this is a ${example}`;
Copy the code
  • And for ES6
    • Basic string formatting. Concatenation by embedding an expression into a string. ${};
    • ES6 backquotes (‘ ‘) directly fix;

An array of

for … Of circulation

  • for … Of is a new iterator in ES6 that allows you to iterate over a data structure with an iterator interface and return the values of each item, as well as for… The difference in is as follows
  1. for … “Of” can only be used on iterables. It is the value returned by the iterator. In can get the key names of all objects
  2. for … In traverses the entire prototype chain of objects and is not recommended for poor performance, whereas for… Of only traverses the current object and not its prototype chain
  3. For an array traversal,for… In returns all enumerable properties in the array (including those on the prototype chain), for… Of only returns the value of the attribute corresponding to the index of the array
  • for … The principle of the “of” loop is also the use of iterator interface internally deployed iterable, if the for… The “of” loop is broken down into the original “for” loop

  • As you can see, the loop continues as long as the second condition ( exists and res.done is true) is met, and each time the object generated by the iterator’s next method is assigned to res, and the value property of res is assigned to for… The done property of res controls whether to continue traversal

3. for… The of loop also supports break,continue,return(if called in a function) and can be used with object destructuring assignments

  • Arr array is used every time for… Each of the “of” loops returns an object ({a:1},{a:2},{a:3}), which is then destructed to find the value of attribute a and assign it to obj.a


(1) Object properties/methods shorthand (common)

1. Es6 allows an object to omit its property name if its property and value are the same

  • It is important to note that **
    • Omit the property name instead of the value
    • The value must be a variable

2. Object property shorthand is often used in conjunction with destructive assignments

  • In combination with the above destructuring assignment, the code here will actually declare the variables x,y, and z, because bar returns an object that has three properties x,y, and z. Destructuring assignment will look for the x,y, and z properties of the expression to the right of the equal sign, and then assign the values to the declared variables x,y, and z

3. Method shorthand

  • Es6 allows the shorthand form to be used when the value of an object’s property is a function (that is, a method)

Module Module

Before the emergence of ES6 Module, modularity has always been the focus of discussion among front-end developers. Faced with the increasing demand and code, there is a need for a solution to break the bloated code into small modules, so there are three modular solutions of AMD,CMD and CommonJs. The former is used on the browser side, and the latter two are used on the server side. Until ES6 Module

  • The ES6 Module is currently not supported by the browser by default and requires the use of Babel. This error is often displayed when writing demos

Characteristics of the Module

  1. The ES6 Module is static, which means it runs at compile time and is improved just like var and function (this makes it possible for Tree shaking)
  2. Automatically adopt strict mode (the top-level this returns undefined)
  3. The ES6 Module can use export {< variable >} to export a named interface or export default to export an anonymous interface

Note: ES6 not only supports the export of variables, but also supports the export of constants. export const sqrt = Math.sqrt; // Export the constant

Note: An import statement can import both default functions and other variables. import default Method, { otherMethod } from ‘xxx.js’;

The module. Js export

The import import

  • The difference is that export {< variable >} exports a reference to a variable, while export Default exports a value
  • In a.js, if the x variable is changed for some reason, it will be immediately reflected in a.js. In a.js, the y variable in a.js will remain the same value

Some differences between ES6 Module and CommonJs

  1. CommonJs outputs a copy of a value,ES6 Module outputs a reference to a variable through export {< variable >}, and export Default outputs a value
  2. CommonJs runs on the server and is designed to be loaded at runtime, that is, the code executes at that line and then goes back to load the Module, whereas ES6 Module is a static output interface that occurs during compilation
  3. CommonJs is run once on the first load and generates a cache, and later loads return the contents of the cache

Import () is loaded dynamically

  • About the ES6 The static compilation of modules makes it impossible to load modules dynamically, but there will always be some requirement to load modules dynamically, so there is a proposal to do this by using import as a function that returns a Promise with the value of the output Module when the Promise is resolved

  • The ES6 notation for lazy loading of routes in Vue uses this technique to dynamically load component rendering views when switching routes

Deconstruction assignment


Destructuring assignment can directly use a property of an object, without the need to access the property. In my opinion, the object destructuring principle is to find the same property name, and then assign the value of the property name of the original object to the corresponding property of the new object. The key is found, and the value is assigned

  • Deconstruction array
var arr = [1, 2, 3, 4];
let[a, b, c, d] = arr; console.log(a); // 1 console.log(b); / / 2Copy the code
  • Deconstruction object
var luke = { occupation: 'jedi', father: 'anakin' };
let {occupation, father} = luke;
console.log(occupation); // jedi
console.log(father); // anakin
Copy the code
  • Vuex uses object deconstruction


It is also recommended because the assignment is more semantic. For function parameters that are objects, you can reduce the declaration of parameters and directly use the properties of the object (if there are too many nesting levels, I personally think it is not suitable to use object destructuring, which is not very elegant).

Rest/Extension operator (common)

The remainder/extension operator is also a very important syntax in ES6, using three points (…) , followed by a data structure containing the iterator interface

Extension operator

  • Arrays, for example, use the extension operators can make “expand” the array, so to understand, the array elements are kept in the collection of a container, and using extension operators can take the container apart, so you only set, you can put these elements set in another array, instead of ES3 in the prototype array concat method

Residual operator

The most important feature of the residual operator is that it replaces arguments

Rest is just a parameter. You can call it whatever you want

  • Access functions of the arguments object is a very expensive operation, before the arguments of the callee, the arguments. The caller was abolished, advice in support ES6 syntax circumstances do not use the arguments in the object, Use the residual operator instead (the arrow function has no arguments, you must use the residual operator to access the parameter collection)

  • Remaining operator can be used together with an array of deconstruction assignment, but must be on the last one, because the rest of the principle of the operator is using the array iterators, it consumes three points behind an array of all the iterator that reads all iterators to generate the value attribute of an object, remaining after the operator cannot in deconstruction assignment, Because the remaining operator consumes all iterators, destructuring an array also consumes iterators, but there are no iterators left, so an error is reported

  • Here first consumes an iterator from the array on the right… Arr consumes all the remaining iterators, and the second example… Arr directly consumes all iterators, leaving last with no iterators left to consume, so an error is reported because it is meaningless

The difference between

The difference between the residual operator and the extension operator is that the residual operator collects the collection and puts it in the array on the right, and the extension operator breaks the array on the right into a collection of elements, which is the opposite

Use extension operators in objects

  • This is ES9 syntax, supports the use of extension in the object in the ES9 operator, said before the array principle is the extension of the operators consume all iterators, but not an iterator object, I personally think that principle may be different, but still can be understood as the key/value pair from the object in the open, it can be on another common object

  • This is similar to another new API in ES6, the object.assign API. They both merge objects, but there are a few differences. The object.assign API fires setters for the target Object, while the Object extension operator does not


  • Use the extension operator to quickly turn a class array into a real array
  • Merging multiple arrays

Function curcurization

Class (ES6)

For developers familiar with Java, Object-C, C # and other pure object-oriented languages, class will have a special feeling. ES6 introduced classes to make object-oriented programming in JavaScript much simpler and easier to understand.

Class constructor {constructor(name,color) { = name; // constructor(name,color) { = name; this.color = color; } // toString is a property on the prototype objecttoString() {
      console.log('name:' + + ',color:' + this.color);


 var animal = new Animal('dog'.'white'); // Instantiate Animal animal.tostring (); console.log(animal.hasOwnProperty('name')); //true
 console.log(animal.hasOwnProperty('toString')); // false
 console.log(animal.__proto__.hasOwnProperty('toString')); // trueClass Cat extends Animal {constructor(action) {// constructor extends Animal {constructor(action) { // Constructor with the default super function will be added, super(), and super().'cat'.'white');
    this.action = action;
  toString() {

 var cat = new Cat('catch') cat.toString(); // the instance cat is an instance of cat and Animal, which is identical to Es5. console.log(cat instanceof Cat); //true
 console.log(cat instanceof Animal); // true
Copy the code


The includes() function determines whether an array contains a specified value, returning true if it does, and false otherwise.

The includes function is similar to indexOf. The following two expressions are equivalent:

arr.indexOf(x) >= 0
Copy the code

Next, we determine whether the number contains an element:

What we did before ES7

Use indexOf() to verify the presence of an element in the array, depending on whether the return value is -1:

let arr = ['react'.'angular'.'vue'];

if (arr.indexOf('react') !== -1)
    console.log('the react there');
Copy the code

Use ES7 includes()

Use includes() to verify the presence of an element in the array for a more intuitive purpose:

let arr = ['react'.'angular'.'vue'];

if (arr.includes('react'))
    console.log('the react there');
Copy the code

Exponential operator

In ES7, the exponent operator ** was introduced, ** has the same function as math.pow (..) Equivalent calculation result.

Do not use the exponential operator

Use the custom recursive function calculateExponent or math.pow () to calculate the exponent:

function calculateExponent(base, exponent)
    if (exponent === 1)
        return base;
        returnbase * calculateExponent(base, exponent - 1); } } console.log(calculateExponent(2, 10)); // Output 1024 console.log(math.pow (2, 10)); // Output 1024 copy codeCopy the code

Use the exponential operator

Use the exponent operator **, just like the +, -, and so on:

console.log(2**10); / / output 1024Copy the code