# You can't answer 80% of the selected interview questions. What else do you want to interview?

0.1 + 0.2 = = = 0.3? Why?

Unequal. In js, javascript uses the Number type to represent numbers (integers or floating-point numbers), following IEEE 754 Standard, a number (1 + 11 + 52) is represented by 64 bit binary: sign bit + exponential bit (order code) + tail code • 1 sign bit, 0 for positive number, 1 for negative number s
• 11 digits (e)
• 52 mantissa, decimal part (i.e. significant number)

The binary representation of 0.1 is: 0.00011001100110011... Which is an infinite circular decimal. Due to the limited storage space, js intercepted the binary, resulting in the loss of accuracy. Similarly, 0.2 is the same. So we get the result of adding two approximate values:

```// Both 0.1 and 0.2 are converted into binary before operation
0.00011001100110011001100110011001100110011001100110011010 +
0.0011001100110011001100110011001100110011001100110011010 =
0.0100110011001100110011001100110011001100110011001100111

// Converted to decimal is exactly 0.300000000000000 4

```

Extension:

In theory, it is impossible to guarantee the accuracy of storing infinite decimals in limited space, but we can deal with it and get the result we want. When you get

When the data like 1.4000000000000000 1 is to be displayed, it is recommended to use toPrecision to round it up and convert parseFloat into a number before displaying it, as follows:

```parseFloat(1.4000000000000001.toPrecision(12)) === 1.4  // True
```

For arithmetic operations, such as ± / *, toPrecision cannot be used. The correct way is to convert the decimal into an integer before operation.

js data type

Basic types: Number, Boolean, null, undefined, String, symbol (newly added in ES6)

Reference type: Object. It contains function, Array and Date

There is also a bigInt(ES2020) in Google's 67 version. It refers to the safe storage and operation of large integers. (but many people don't take this as a type).

How is js integer represented?

Represented by Number type, follow IEEE 754 Standard, a number (1 + 11 + 52) is represented by 64 bit binary, and the largest security number is math Pow (2,53), for 16 bit binary.

What is the storage space of Number()? What if the background sends a number that exceeds its maximum

The maximum safe number of js is math Pow (2,53), 53 significant digits, value: 9007199254740992. If it is exceeded, truncation will occur, which is equal to the maximum number that js can support. For example, 90071992547409222, the obtained value will be inaccurate, that is, 900719925474099200.

Write code: the implementation function can deeply clone basic types

Shallow clone:

``` function  shallowClone(obj){
let cloneObj = {};

for(let i in obj){
cloneObj[i] = obj[i]
}
return cloneObj;
}
```

Deep cloning:

• Consider foundation type
• reference type
• RegExp, Date and function are not JSON safe
• The constructor will be lost, and all constructors point to Object
• Crack circular reference
```function deepCopy(obj){
if(typeof obj === 'object'){
var result = obj.constructor === Array ?[]:{};
for (var i in obj){
result[i] = typeof obj[i] === 'object'?deepCopy(obj[i]):obj[i];
}
}else{
var result = obj;
}
return result;
}
```

What is the event flow?

The event flow is the sequence in which web page elements receive events. The event flow specified in 'DOM2 level event' includes three stages:

• Event capture phase
• At target stage
• Event bubbling phase

The first event capture provides an opportunity to intercept the event. Then there is the actual target acceptance event. The last stage is the event bubbling stage, where you can respond to events. Although the capture phase is not allowed to respond to events in the specification, it will actually be executed, so there are two opportunities to obtain the target object.

```<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Event Bubbling </title>
<body>
<div>
<p id="parEle">I am the parent element    <span id="sonEle">I am a child element</span></p>
</div>
</body>
</html>
<script type="text/javascript">
var sonEle = document.getElementById('sonEle');
var parEle = document.getElementById('parEle');

}, false);
}, true);

}, false);
}, true);

</script>
```

When there are multiple nested elements, that is, the event handler is called in the capture phase and in the bubble phase, the event executes the event handler in the order of dom event flow:

• Parent capture
• Sub level bubbling
• Child capture
• Parent bubbling

When the event is in the target stage, the calling order of the event depends on the writing order of the bound event. According to the above example, call the event handler in the bubbling stage first, and then call the event handler in the capture stage. alert "subset bubbling" and "subset capture".

How is the event implemented?

The publish based subscription mode is that the code of relevant events will be read when the browser is loaded, but it will be executed only when the specific event is triggered.

For example, clicking a button is an event, and the code segment responsible for processing time is usually called event handler, that is, the action of [start the display of dialog box].

On the Web side, DOM events are common:

• DOM0 level events, bind on event directly to html elements, such as onclick. If you cancel, DOM Onclick = null, there can only be one handler for the same event, and the latter will overwrite the former.
• DOM2 level events: register events through addEventListener and delete events through removeEventListener. An event can have multiple event handlers that execute in order to capture events and bubble events.
• DOM3 level events, adding event types, such as UI events, focus events, and mouse events

What happens to a new function?

Construction call:

• Create a new object
• The object will be connected by [[prototype]] and the [[prototype]] of the new object will be linked to the constructor The object to which the prototype points
• This new function will be bound to this of the function call
• If the function does not return another object, the function call in the new expression will automatically return the new object

new is a constructor. What happens if the function returns return {}, return null, return 1 and return true?

If the function returns an object, the new function call returns the return object of the function. Otherwise, it returns the new object created by new

What's the use of symbol?

Can be used to represent a unique variable to prevent naming conflicts. You can also use that symbol will not be traversed by conventional methods (except Objet.getOwnPropertySymbols), so it can be used to simulate private variables.

It is mainly used to provide traversal interface and arrange symbol Only objects of iterator can use for Of loop, which can uniformly process data structures. After calling, an iterator object will be returned, including a next method. After using the next method, the two return values value and done respectively represent the value of the current execution position of the function and whether the traversal is completed.

Symbol.for() can access symbol globally

What is a closure?

A closure is a function that has access to a variable in the scope of another function.

The whole execution process of javascript code is divided into two stages: code compilation stage and code execution stage. The compilation stage is completed by the compiler, which translates the code into executable code. The code scope rule will determine that the execution stage is completed by the engine. The main task is to execute executable code, and the execution context is created at this stage. ###### What is scope?

There are only two scopes in ES5: global scope and function scope. In javascript, we define a scope as a set of rules, which are used to manage how the engine searches variables (variable names or function names) according to identifier names in the current scope and nested sub scopes

###### What is a scope chain?

First, understand the scope chain. When accessing a variable, when executing this code, the compiler will first look for the identifier from the current scope. If it is not found, go back to the parent scope. If the parent scope has not been found, continue to look up until the global scope, and the scope chain, It is composed of a series of variable objects with the current scope and the upper scope, which ensures the orderly access of the currently executed scope to the variables and functions that meet the access permission.

###### The essence of closure

There are references to parent scopes in the current environment

###### What is closure

Closure is A special object, which consists of two parts: the execution context (code A) and the function created in the execution context (code B). When B executes, if the value of the variable object in A is accessed, the closure will be generated, and the function name of execution context A is used to refer to the closure in Chrome.

###### How to generate closures in general
• Return function
• Functions are passed as arguments
###### Application scenario of closure
• Coriolis bind
• modular

What is NaN and what will be output with typeof?

Not a Number means non number, typeof NaN = = = 'number'

js implicit conversion, display conversion

Generally, valueOf will be called first when converting a non basic type. If valueOf cannot return the value of the basic type, toString will be called

###### Strings and numbers
• '+' operator. If one of them is a string, they are converted to a string, and then string splicing is performed
• The '-' operator, converted to a number, and subtraction (- A, a*1, a/1) can be implicitly cast
###### Boolean to number
• 1 + true = 2
• 1 + false = 1
###### Convert to Boolean
• Second in for
• while
• if
• Ternary expression
• ||(logical or) & & (logical and) left operand
###### Symbol
• Cannot be converted to numbers
• Can be converted to Boolean values (all true)
• Can be converted to the string "symbol (cool)"
###### Loose equality () and strict equality (=)
• Loose equality allows cast, while strict equality does not
###### String and number
• Convert to numbers and compare
###### Other types and Boolean types
• First convert the boolean type to a number, and then continue the comparison
###### Object and non object
• Execute the toPrimitive of the object and continue the comparison
###### False value list
• undefined
• null
• false
• +0，-0，NaN
• ""

What does bind, call and apply mean?

They are all methods of functions

• call: Array.prototype.call(this，args1,args2)
• apply: Array.prototype.apply(this，[args1,args2]

Four rules:

• Default binding: there are no other modifiers (bind, apply, call). It is defined to point to global objects in non strict mode and to undefined in strict mode
```function foo() {
console.log(this.a);
}

var a = 2;
foo();
//2
```
• Implicit binding: whether the calling location has a context object, or whether it is owned or contained by an object, then the implicit binding rules will bind this in the function call to this context object. Moreover, only the upper or last layer of the object attribute chain plays a role in the call.
```function foo() {
console.log(this.a);
}

var obj = {
a: 2,
foo: foo,
}

obj.foo(); // 2
```
• Display binding: this binding is displayed by running call and apply on the function
```function foo() {
console.log(this.a);
}

var obj = {
a: 2
};

foo.call(obj);
```
• Displays the hard binding of the binding
```function foo(something) {
console.log(this.a, something);

return this.a + something;
}

function bind(fn, obj) {
return function() {
return fn.apply(obj, arguments);
};
}

var obj = {
a: 2
}

var bar = bind(foo, obj);
```

New binding, new calling the function will create a new object and bind this object to this of the function call

• When new is bound, if new is a hard bound function, the hard bound this will be replaced by the new object
```function foo(a) {
this.a = a;
}

var bar = new foo(2);
console.log(bar.a)
//2
```

Handwritten bind, apply, call

```//call
Function.prototype.call = function (context,...args) {
context = context || window;

const fnSymbol = Symbol("fn");
context[fnSymbol] = this;

context[fnSymbol](...args);
delete context[fnSymbol];
}
```
```//apply
Function.prototype.apply = function (context,argsArr) {
context = context || window;

const fnSymbol = Symbol("fn");
context[fnSymbol] = this;

context[fnSymbol](...argsArr)
delete context[fnSymbol]
}
```
```// bind
Function.prototype.bind = function(context,...args) {
context = context || window;
const fnSymbol = Symbol("fn");
context[fnSymbol] = this;

return function (..._args){
args = args.concat(_args);

context[fnSymbol](...args);
delete context[fnSymbol];
}
}
```

setTimeout(fn,0) how long? Cai Zhixing, EventLoop

setTimeout is put into the queue in order, and then wait until the function call stack is cleared before execution. The order in which these operations enter the queue is determined by the set delay time.

Handwritten Promise principle

```class MyPromise{
constructor(fn){
this.resolvedCallbacks = [];
this.rejectedCallbacks = [];

this.state = 'PENDING';
this.value = '';

fn(this.resolve.bind(this),this.reject.bind(this))
}
resolve(value){
if(this.state == 'PENDING'){
this.state = 'RESOLVED';
this.value = value;

this.resolvedCallbacks.map(cb => cb(value));
}
}

reject(value){
if(this.state == 'PENDING'){
this.state = 'REJECTED'
this.value = value

this.rejectedCallbacks.map(cb => cb(value));
}
}

then(onFulfilled,onRejected){
if(this.state === 'PENDING'){
this.resolvedCallbacks.push(onFulfilled);
this.rejectedCallbacks.push(onRejected);
}

if(this.state === 'RESOLVED'){
onFulfilled(this.value);
}

if(this.state == 'REJECTED'){
onRejected(this.value)
}
}
}
```