ES6 is often used in development, but some of the basic definitions are often ignored. Take this, record with the way of total interview question, if there is wrong place, please also point out, thank you!

Let const var

The scope of a variable is the part of an algorithmic function that we can access (or, when using function scope, a function). There are local variables and global variables.

Let const var

  • letconstThe variables defined are constants that have block-level scope.
  • varThere is no concept of block-level scope for defined variables, but there is variable promotion, that is, variables can be used before they are declared,letconstIs not.
  • beconstletDeclared constants or variables cannot be declared twice (in the same scope),varVariables can be declared repeatedly, overwriting the previous principle definition with the last one defined.
  • constTo define a constant, assign an initial value to it; otherwise, an error is reported.let.varNo initial value can be assigned during initialization.
  • constThe definition of theBasic data typesConstants cannot be modified values, definedReference data typeConstant references the internal property values of data that can be modified.

Extension question 1: What scope does JS have? What is block-level scope?

JS scope adopts this scope mechanism. There are global scopes, function scopes and block-level scopes

Global scope

The Window global scope

Function scope

A function is a footer local scope. Variables that are local to a function are not allowed to be accessed externally.

When a variable cannot be found in the current scope after nesting, the compilation engine will continue to look in the outer nested scope (the parent scope at the time of the definition is not run-time) until the variable is found. Or it reaches the outermost scope (the global scope).

This layer-by-layer look-up mechanism is the look-up rule of the scope chain.

If the variable is not found in its outermost layer, strict mode throws an exception, and non-strict mode defines the variable in its outermost (global) layer

Block-level scope

Variables or constants defined by let,const. Block-level scopes are formed. Block-level scope refers to a scope space in which variables declared by const let are not visible outside that scope.

Common functions,if, for, and try/catch all form a block-level scope.

Note that the for bracket is also a separate scope space.

Extension Question 2: What is variable promotion?

My personal understanding is that variables or functions can be used before they are declared.

Here’s an example:

// Variable definition console.log(a); // undefined console.log(b); // Uncaught ReferenceError: b is not defined console.log(c); // Cannot access 'x1' before initialization var a = 1; let b = 2; const c = 3;Copy the code

Variables defined by var are promoted. Declarations made by let and const are not

// The function promotes console.log(fn1); // undefined console.log(fn2); ƒ fn2() {} var fn1 = function() {}; function fn2() {}Copy the code

A function is promoted through the function keyword, but the function expression is not promoted

var num = 1; function fn3() { console.log(num); // undefined var num = 0; } fn3(); console.log(num); / / 1Copy the code

Each scope has a promotion operation, and the declaration is promoted to the top of its scope

console.log(g) // function g(){}
var g = 1
function g(){}
console.log(g) // 1

console.log(g) // function g(){}
function g(){}
var g = 1
console.log(g) // 1
Copy the code

The function keyword has a higher promotion priority than the var keyword. So the first console.log(g) prints out the g() method, and when the code continues down and encounters function g(){}, the g() function is declared to do nothing, but overwrites the assignment of g=1, so the next console.log(g) prints out 1.

If a variable or function has a duplicate declaration, the last declaration takes precedence.

So, variable and function promotions are characterized by:

  • throughvarThe defined variable will be promoted, whileletandconstStatements made do not promote.
  • throughfunctionFunctions defined by keywords are promoted, but function expressions are not.
  • varThe statement itself will be promoted, but the packageParenthetical function expressionAnd the assignment operation insideWill not raise.
  • Each scope is promoted,The statementWill beThe ascent toWhere theTop of the scope.
  • functionfunctionKeyword promotion takes precedence over variablesvarThe keyword.

Reference: scope of JS

The difference between Set, Map, WeakSet and WeakMap

A detailed description of Set, Map, WeakSet and WeakMap and the use of and Set and Map data structures

Set

  • It is a kind ofClass array data structure.Members have unique values, there is no duplicate value
  • Accepts an array (or an array-like object) as a parameter
  • You can iterate, and iterate order is insertion order

WeakSet structure is similar to Set, which is also a collection of non-repeating values.

WeakSet and Set difference

  • WeakSetA member can only beobjectCannot be any other type of value
  • WeakSetObjects inA weak reference, i.e.,The garbage collection mechanism does not consider WeakSet’s reference to this objectThat is, if the object is no longer referenced by other objects, the garbage collection mechanism automatically reclaims the memory occupied by the object, regardless of the object’s existenceThe WeakSetIn the. This feature means that WeakSet members cannot be referenced, soWeakSet is not traversalAnd there is nosizeProperties.

WeakSet is useful for storing DOM nodes without worrying about memory leaks when they are removed from documents.

Map

  • It is a kind ofAn object-like data structure, is also a set of key-value pairs,”keyThe scope of”Not limited to strings.Values of all types, including objects, can be used as keys.
  • You can accept an array as an argument to theThe members of the array areOne by one representationAn array of key-value pairs.
  • The Map keyIt’s actually related toMemory addressBound, as long as the memory address is different, as two keys.
  • ifMapThe key is a value of a simple data type (number, Boolean, string), then only twoThe values are exactly the same, the MapAs a bond
  • MapThe traversal order of is the insertion order

Difference between WeakMap and Map

  • WeakMapOnly objects are accepted as key names (nullExcept)
  • Key nameIs the object’sA weak reference(The garbage collection mechanism does not take this reference into account), so its corresponding object mayIt's automatically recycled.
  • There is no traversal operation (i.ekey(),values()andentries()Method), neithersizeProperties;
  • It can’t be emptied, that is, not supportedclearMethods. This has to do withWeakMapIs not counted as a reference and is ignored by the garbage collection mechanism. Therefore, WeakMap has only four methods available:Get (), set(), has(), delete().

Basically, the special use of WeakMap is that the object to which its key corresponds may disappear in the future. The WeakMap structure helps prevent memory leaks.

What’s the difference between an arrow function and a normal function?

  • Arrow functions are syntactically cleaner than normal functions
  • Arrow function doesn’t have anyprototype(prototype), so the arrow function itself does notthis
  • The arrow function’s this pointer is inherited from the first normal function in the outer layer at function definition, so the arrow function’s this pointer is determined at definition and never changes.
  • usecall.apply.bindCan’t change the “this” in the arrow function
  • Because arrow functions don’t have subsetsthisAnd it’s not gonna change, soArrow functions cannot use definition constructors, otherwise usenewThe keyword will report an error
  • There’s nothing inside the arrow functionarguments, butrestparameter(…). Instead ofargumentsObject to access the argument list of the arrow function
  • Arrow functions cannot be usedGeneratorFunction, cannot be usedyieldThe keyword

Examples of arguments:

Function A(A){console.log(arguments); } A (1, 2, 3, 4); ƒ // [1, 2, 3, 4, callee: ƒ, Symbol(symbol.iterator): ƒ] // arrow function let B = (B)=>{console.log(arguments); },92,32 (2 B); // Uncaught ReferenceError: arguments are not defined // rest parameters... let C = (... c) => { console.log(c); } C (3,82,32); / / / 3, 82, 32,Copy the code

Tell me what you understand about Promise

Promise, allows asynchronous operations to be expressed as a flow of synchronous operations, avoiding layers of nested callback functions. Promise objects provide a unified interface that makes it easier to control asynchronous operations

Disadvantages of Promises:

  • First of all, there’s no cancellationPromiseOnce created, it is executed immediately and cannot be cancelled midway.
  • Second, if you don’t set the callback function,PromiseErrors thrown internally are not reflected externally.
  • Third, when inpendingWhen you are in the state, you cannot tell what stage you are in (just started or almost finished).

The state of the Promise

As ECMAScript 6 gets you started, promises have three states:

  1. Pending
  2. Completed (Resolved)
  3. I have rejected your offer.

What problem did Promise solve

Promise solves the previous callback hell problem, and promises implement chained calls, meaning that each call to THEN returns a Promise, and a completely new Promise. Because the Promise state is immutable. If you use return in THEN, the value of return is wrapped in promise.resolve.

How does Promise block errors

  • .catch

The catch method catches errors, but only synchronous errors, not asynchronous errors.

  • userejectThrows an error, and the error is continually returned to the next one, which must be in each onethenUse insidethowThrow mistakes out, or they can’t becatchCapture, in fact, can not be againthowError inpromisenormalcatchOk, in asynchronyrejectIt’s going to be right at the endcatchTo the.

Errors in promises do not affect the running of the outer layer, and window.onerror is not detected.

For a detailed description of error interception for Promises, go to error interception for Promises

Modular development

Take a large program and break it up into smaller, interdependent files and put them back together in a simple way. The function of the module consists of two commands: export and import. The export command is used to specify the external interface of a module, and the import command is used to input functions provided by other modules.

The export command

A module is an independent file. All variables inside the file are not available externally. If you want outsiders to be able to read a variable inside a module, you must use the export keyword to output that variable.

Use:

Var name= 'lisa'; var name= 'lisa'; var age= 18; export { name, age}; Function fn1() {function fn1() {... } function fn2() { ... } export {fn1 as checkNanme1, fn2 as checkNanme2} // Rename asCopy the code

If you are in block-level scope, an error is reported, as is the import command. This is because you can’t do static optimizations when you’re in a conditional block, which goes against the design of the ES6 module.

The import command

Use the import command to load the module

Note that the variables entered by the import command are read-only because it is essentially an input interface. That is, it is not allowed to rewrite the interface in the script that loads the module (if you are importing an object, it is ok to rewrite the object’s properties, but it is not recommended to change its value lightly).

Export the default command

Specify default output for the module

The export default command is used to specify the default output of the module. Obviously, a module can have only one default output, so the export default command can only be used once. Therefore, the import command is not followed by parentheses, because it can only correspond to the export default command.

Essentially, export default simply prints a variable or method called default (specifying the external interface as default) and then allows you to call it whatever name you want. So it can’t be followed by variable declarations.

Reference:

A normal function of the arrow function

Error handling of promises