This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

The introduction

In this paper, some important principles in JS are summarized in the form of questions. The chapters are organized from easy to difficult, and readers are advised to read them in chapter order. I hope that after reading this article, readers will have some inspiration to think, and also have a certain understanding of their JS mastery, to make up for the omissions, and to have a better grasp of JS.

The author will also stand in the perspective of the interviewer to answer the following questions, and appropriate analysis.

1. What data types do JavaScript have, and what are the differences?

There are eight data types in JavaScript: Undefined, Null, Boolean, Number, String, Object, Symbol and BigInt.

  • Basic data types: Undefined, Null, Boolean, Number, String, Symbol, BigInt
  • Reference data type: Object

Symbol and BigInt are new data types in ES6:

  • Symbol represents a unique and immutable data type created to address possible global variable conflicts.
  • BigInt is a numeric type of data that can represent integers in any precision format. Using BigInt, you can safely store and manipulate large integers, even if the Number is outside the safe integer range that Number can represent.

The difference between the two types lies in the storage location:

  • Basic data types are simple data segments directly stored in the stack, occupying small space and fixed size. They are frequently used data, so they are stored in the stack.
  • Reference data types are objects stored in the heap that occupy a large space and are of variable size. If stored in the stack, it will affect the performance of the program; The reference data type stores a pointer on the stack to the starting address of the entity in the heap. When the interpreter looks for a reference value, it first retrieves its address in the stack and then retrieves the entity from the heap.

2. What are the methods of data type detection

The following three methods can be used for data type judgment, but all of them have certain limitations, so the type judgment method will be rewritten in the actual development process of the project.

Typeof: Undefined, Boolean, Number, String, Symbol, Function, etc. Typeof returns the basic typeof a variable.

Instanceof: Complex reference data types can be accurately identified. Instanceof returns a Boolean value.

Object. The prototype. ToString. Call () : this method is invoked, the unity of the format “[Object] Xxx” string.

function typeOf(obj) {
   let res = Object.prototype.toString.call(obj).split(' ')[1]
   res = res.substring(0, res.length - 1).toLowerCase()
   return res
}

typeOf([])        // 'array'
typeOf({})        // 'object'
typeOf(new Date)  // 'date'
Copy the code

What is the difference between null and undefined

Null and undefined are both basic data types. Undefined means undefined and NULL means an empty object

JS was originally designed with Null, but when typeof is used to judge, Null typing returns “object”. Therefore, JS authors thought that a Null data type would be judged as a reference type, so they created undefined

4.为什么 0.1 + 0.2 != 0.3 ?

0.1 + 0.2! = 0.3 is due to the loss of accuracy in the process of base conversion and advanced operation.

Because the bottom of the computer is the use of binary number on the order of operation, in the conversion process between the precision will be lost 0.1 + 0.2! = 0.3?

In general, toFaild() is used in projects to round data, or multiply by 10 to an integer and then divide by 10 after precision loss.

5. Let, const, var

(1) Block-level scope: block scope is included by {}, let and const have block-level scope, var does not have block-level scope. Block-level scopes solve two problems in ES5:

  • Inner variables may override outer variables
  • Loop variables used to count are leaked as global variables

(2) Variable promotion: var has variable promotion, let and const have no variable promotion, that is, variables can only be used after the declaration, otherwise an error will be reported.

(3) Add global attribute: browser global object is window, Node global object is global. Var declares a global variable and adds it as a property of the global object, but let and const do not.

(4) Repeated declaration: when var declares a variable, it can repeat the declaration of the variable, and the variable with the same name declared after will overwrite the traversal declared before. Const and let do not allow variables to be declared twice.

(5) Temporary dead zone: a variable is not available until it is declared with let, const. This is grammatically called a temporary dead zone. Variables declared using VAR do not have temporary dead zones.

(6) Initial value setting: When declaring variables, var and let do not need to set initial values. A const declaration variable must have an initial value.

(7) Pointer to: let and const are new syntax for creating variables in ES6. Let creates variables that can be pointer pointed to (can be reassigned). But const variables are not allowed to change the pointer.

6. Talk about the difference between arrow functions and normal functions

(1) Arrow functions are more concise in code writing than ordinary functions

(2) Arrow function cannot be new

(3) Arrow functions do not have their own this

(4) Arrow functions have no arguments of their own

Arrow function has no prototype

(6) Arrow functions cannot be used as Generator functions and the yeild keyword cannot be used

(7) The this pointer inherited from the arrow function never changes

(8) Call (), apply(), bind() and other methods cannot be used to change the direction of this in arrow function

7. Talk about your understanding of light copy

Shallow copy refers to copying only the reference to the object, so the copy ends up pointing to the object in the heap memory of the parent object. If either the copy or the parent object modifies the object, the copy or the parent object will be changed in the same way

Deep copy directly copies the parent object in the heap, eventually creating a new object in the heap, independent of the parent object. Deep-copied objects are independent of, but consistent with, the parent object. When the deep copy is complete, changes to the parent object will not affect the deep copy.

Parse () nested json.stringify () for deep copies and object.assign () for shallow copies

Talk about your understanding of the new implementation

  1. First create a new empty object.
  2. According to the prototype chain, set the null object__proto__Of the constructorprototype
  3. The constructor’s this points to the object and executes the constructor’s code (adding attributes to the new object).
  4. Determine the return type of the function and, if it is a reference type, return an object of that reference type.

9. Talk about your understanding of scopes and scope chains

Scope: A scope is the area where variables are defined. It has a set of rules for accessing variables that govern how the browser engine looks up variables (identifiers) in the current scope and nested scopes.

Scope chain: In the execution of a function, each variable, can retrieve from where to obtain and store data, the process from the scope chain head, which is starting from the active object search, find the identifier with the same name, use this when I found it identifiers corresponding variables, if not then move on to the next object of the search scope chain, if you search for all the objects are not found, The identifier is considered undefined. During the execution of the function, each identifier goes through such a search process.

Since the scope chain is the stack structure, the global variable is at the bottom of the stack, and the stack will be traversed every time the global variable is accessed. This will definitely affect efficiency, so the definition of global variables should be reduced to optimize.

The prototype chain takes precedence over the scope chain for variable lookups. The JS engine looks first in the function AO object, then in the prototype chain, then in the scope chain.

10. Talk about your understanding of prototypes and prototype chains

Prototype: In JS we use constructors to create objects. Each constructor has a prototype property value inside it. This property value is an object containing properties and methods that can be shared by all instances of the constructor

Stereotype chain: The basic idea is to use stereotypes to make one reference type inherit the properties and methods of another. In JS, an object’s prototype chain is represented by the proto property. When looking for an object’s property, JS traverses up the prototype chain until it finds the property with the given name

The __proto__ attribute is only publicly accessible in firefox or Chrome browsers.

In simple terms, every object initializes a property inside it, which is proto, and when we access an object’s property, if the object doesn’t have that property inside it, then it looks for that property in __proto__, which in turn has its own __proto, and so on and so forth, This is the concept of a prototype chain.

The prototype chain takes precedence over the scope chain for variable lookups. The JS engine looks first in the function AO object, then in the prototype chain, then in the scope chain.

11. Tell me what you understand about promises

Promise is a solution to asynchronous programming. It is a constructor, and you can get an instance of it through New Promise. There are two common functions and one common method on promises. Resolve (a successful callback), reject (a failed callback), and.then().

More commonly used at work are the promise.all () and promise.race methods

Promse.race is a race, which means that a Promise. Race ([P1, P2, P3]) returns the fastest result, regardless of whether the result itself is a success or a failure.

Promise.all can wrap multiple Promise instances into a new Promise instance. Also, success and failure return different values, with success returning an array of results and failure returning the first rejected state.

12. How do I synchronize asynchronous operations

1. Then chain of Promise, disadvantages: It is not easy to investigate which link is wrong in the THEN chain, and the code is not beautiful (not recommended)

2. The async/await: The underlying implementation of async and await is based on a Generator function, which returns an iterator object. Each time the iterator object calls the next method, the yield expression of the Generator function returns the value of the object’s value property.

13. Tell me what you understand about closures

DefineProperty is wrapped around Object.definerecvite to form a closure environment. The main reason is that internal functions may need some local variables, but they also need to avoid contaminate the whole world. Hence the introduction of closures.

Closures are not often used in work because they can cause memory leaks and have some negative impact on processing speed because closure look-up variables go through the scope chain

So for the overall performance of my code, I rarely use closures unless I have to

14. Tell us your understanding of the garbage collection mechanism

In JavaScript memory management, there is a concept called reachable, which is that values that are somehow accessible or available are guaranteed to be stored in memory and reclaimed if they are not

JS garbage collection mechanism is the most common tag cleaning algorithm and reference counting algorithm, but after the V8 engine major browsers mainly use tag cleaning algorithm for garbage collection

Reference counting method, which is actually the earlier a garbage collection algorithm, the object is no longer needs to simplify it defined as object there is no other object references to it, if there is no reference to the object reference (zero), the object will be recycled garbage collection mechanism, now rarely used this algorithm, because it has a lot of problems

Mark clearing algorithm is divided into two stages: mark and clear. Mark stage marks all active objects, and clear stage destroys no mark (inactive objects)

But mark sweep algorithm has a big weakness, after is clear, the rest of the object memory location is the same, can also lead to free memory space is discrete, the memory fragments, and the remaining free memory is not a block, it is made up of different sizes of memory memory list, it will get sucked out of the memory allocation problem. The mark-compact algorithm can effectively solve this problem. Its marking phase is no different from that of the mark-clean algorithm, except that after marking, the mark-compact algorithm moves the living objects (i.e., objects that do not need to be cleaned up) to one end of memory, and finally cleans up the border memory

15. Talk about your understanding of Event Loop

JavaScript is a single-threaded language where everything is done on a single thread. When faced with a large number of tasks or a time-consuming task, such as loading a high-resolution image, the page will appear “suspended” because the JavaScript will not stop and will not respond to the user’s actions. To prevent the main thread from blocking, JavaScript has the concept of synchronous and asynchronous. So JavaScript uses a mechanism to handle both synchronous and asynchronous operations called Event loops.

  • All synchronous tasks are executed sequentially on the main thread, forming an execution stack (call stack), and asynchronous tasks are placed in a task queue

  • When the tasks in the execution stack are completed, check whether the micro-tasks in the micro-task queue are empty and execute them. If the micro-tasks are encountered in the micro-task execution process, add them to the end of the micro-task queue and continue to execute them to complete all the micro-tasks

  • After the execution of the micro task, check whether the macro task is empty in the task queue, and then take out the macro task that enters the queue first and push it into the execution stack to execute its synchronization code

  • Then go back to step 2 to perform the microtasks in that macro task, and repeat until the macro task is also completed, and so on

recommended

If you want to continue learning about browsers, you can watch another article by me on juejin.

If you want to continue to learn the principles of CSS, you can watch the author of another article (interview treasure guide) CSS chapter – Nuggets (juejin. Cn)

If you want to continue to learn the Vue principle of readers, you can watch another article by the author [interview treasure guide] high frequency front end questions of Vue principle of readers – nuggets (juejin. Cn)

If there are readers who want to continue to learn the common method of handwriting JS, you can watch the author of another article [interview treasure guide] high frequency front end questions of handwriting commonly used JS method – digging gold (juejin. Cn)

conclusion

This article is the author’s personal study notes, if there are fallacies, please inform, thank you! If this article has been helpful to you, please click the “like” button. Your support is my motivation to keep updating.