Note: the number (xx) before each question represents the frequency of this question. This JS basis is based on the questions and corresponding answers and reference links in the front face of 30+ articles. The content of the article is arranged by myself who got the Offer.

Q: 0.1 + 0.2 === 0.3? Why is that?

JavaScript uses the Number type to represent numbers (integer or floating point). It follows the IEEE 754 standard to represent a Number in 64 bits (1 + 11 + 52).

  • 1 sign bit, 0 for positive, 1 for negative s
  • 11 Exponent bit (e)
  • 52 mantissa, fractional part (i.e. significant number)

MAX_SAFE_INTEGER = math.pow (2, 53) -1, which is 16 bits when converted to an integer, so 0.1 === 0.1, because they are equal after the valid bits are removed by toPrecision(16).

When two numbers are added, they will be converted into binary first. When 0.1 and 0.2 are converted into binary, the mantail will have an infinite loop, and then the order operation will be carried out. JS engine will truncate the binary, so the accuracy will be lost.

So conclusion: precision loss may occur in base conversion and pairwise operations

Refer to the link

  • Juejin. Im/post / 5 b90e0…

(4) Q: JS data type

BigInt (ES2020) Reference type: Object, Object subtype (Array, Function)

Refer to the link

  • Juejin. Im/post / 5 b2b0a…
  • Developer.mozilla.org/zh-CN/docs/…

Q: how is the JS integer represented?

  • It is represented by the Number type, in accordance with the IEEE754 standard, and is represented by a 64-bit Number, (1 + 11 + 52). The maximum safe Number is math.pow (2, 53) -1, for 16-digit decimal. (Sign bit + exponent bit + significant decimal bit)

Q: How much storage space does Number() have? What if the background sends a number that exceeds its maximum

Math.pow(2, 53), 53 is a significant number, truncation occurs, and is equal to the maximum number that JS can support.

(4) Write code: implement functions that can deeply clone basic types

Shallow cloning:

function shallowClone(obj) {
  let cloneObj = {};
  
  for (let i in obj) {
    cloneObj[i] = obj[i];
  }
  
  return cloneObj;
}
Copy the code

Deep cloning:

  • Consider base types
  • Reference types
    • RegExp, Date, and functions are not JSON-safe
    • Constructor is lost, and all constructors point to Object
    • Breaking circular references
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;
}
Copy the code

Q: Event flow

Event flow is the order in which a webpage element receives events. The event flow specified by “DOM2 event “includes three phases: event capture phase, target phase, and event bubble phase. Event capture occurs first, providing an opportunity to intercept the event. Then there is the actual target acceptance event. The final phase is the time bubble phase, where you can respond to events. Although the capture phase is not allowed to respond to events in the specification, it actually executes, so there are two chances to get the target object.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The event bubbling</title>
</head>
<body>
    <div>
        <p id="parEle">I'm the parent element<span id="sonEle">I'm a child element</span></p>
    </div>
</body>
</html>
<script type="text/javascript">
var sonEle = document.getElementById('sonEle');
var parEle = document.getElementById('parEle');

parEle.addEventListener('click'.function () {
    alert('Parent Bubble');
}, false);
parEle.addEventListener('click'.function () {
    alert('Parent capture');
}, true);

sonEle.addEventListener('click'.function () {
    alert('Sub-bubble');
}, false);
sonEle.addEventListener('click'.function () {
    alert('Child capture');
}, true);

</script>
Copy the code

When the event handler is invoked for container and nested elements, that is, during the capture phase and during the bubble phase: The event executes the event handler in the order of the DOM event stream:

  • The parent trap
  • The child capture
  • Children bubble
  • The parent bubbling

And when the event is in the target phase, the event invocation order is determined by the writing order of the binding event. As shown in the above example, the event handler in the bubble phase is called first, and then the event handler in the capture phase is called. Alert “subset bubble” and “subset capture” in turn.

Compatible with IE

  • attchEvent(‘on’ + type, handler)
  • detachEvent(‘on’ + type, handler)

Refer to the link

  • Juejin. Im/entry / 5826 b…

Q: How are events implemented?

Based on a publish-subscribe pattern, event-related code is read when the browser loads, but is not actually executed until the actual event is triggered.

Clicking a button, for example, is an Event, and the piece of code that handles the Event is often called an Event Handler, which is the action that “starts the display of the dialog box.”

On the Web side, we often see DOM events:

  • Dom0-level events are directly bound to HTML elements with on-event, such as onclick. If cancelled, dom.onclick = null, the same event can only have one handler, and later handler will override the previous one.
  • Dom2-level events, register events with addEventListener, remove events with removeEventListener, an event can have multiple event handlers, execute in sequence, capture events and bubble events
  • DOM3 level events, added event types such as UI events, focus events, and mouse events

Refer to the link

  • zhuanlan.zhihu.com/p/73091706

Q: What happens to a function called new

Construct call:

  • Create an entirely new object
  • This object will be wired by the [[Prototype]] execution, linking the new object’s [[Prototype]] to the object referred to by the constructor
  • This new object is bound to the this function call
  • If the function returns no other object, then the function call in the new expression automatically returns the new object

Q: New a constructor if the function returnsreturn {}return nullreturn 1return trueWhat’s going to happen?

If a function returns an object, then the call to new returns the object returned by the function, otherwise returns the new object created by new

Q:symbolWhat’s the use

Can be used to represent a unique variable to prevent name conflicts. But what else? I didn’t think of other USES are directly answer I don’t know, still can use the symbol will not be routine method (in addition to the Object. GetOwnPropertySymbols) traversal, so can be used to simulate the private variables.

It is mainly used to provide the traversal interface. Only objects with symbol. Iterator can use the for···of loop, which can process the data structure uniformly. This call returns an iterator object containing a next method. Using the next method, the return values value and done indicate the value of the function’s current execution position and whether or not the iterator is complete.

Symbol is accessed globally by symbol.for ()

(3) Q: What is a closure?

Closures are functions that have access to variables in the scope of another function

The entire execution process of JavaScript code is divided into two stages, code compilation stage and code execution stage. The compile phase is done by the compiler, translating the code into executable code, where the scope rules are determined. The execution context is created in the execution phase, which is completed by the engine and the main task is to execute the executable code.

What is scope?

There are only two kinds of scopes in ES5: global scope and function scope. In JavaScript, we define scope as a set of rules that govern how the engine looks for variables (variable names or function names) based on identifier names in the current scope and nested sub-scopes

What is a scope chain?

Must first understand the scope chain, when to access a variable, when performing this code, the compiler will begin from the current scope to find whether have this identifier, if not found, will go to the parent scope to find, if the parent scope has yet to find a continued upward lookup, until the global scope, the scope chain, It is composed of a series of variable objects in the current scope and the upper scope, which ensures that the currently executing scope has ordered access to the variables and functions that conform to the access permission.

The nature of closure generation

There is a reference to the parent scope in the current environment

What is a closure

Closure is A special kind of object, it consists of two parts: the execution context (code A), was founded in the execution context and the function of the code (B), when B execution, if access to A variable in the the value of the object, the closure will produce, and in Chrome, using A function name generation refers to the execution context A closure.

How do you generate closures in general

  • Returns the function
  • Functions are passed as arguments

Closure application scenarios

  • Currie bind
  • The module

Refer to the article

  • Segmentfault.com/a/119000001…

Q: What is NaN, and what does typeof print?

Typeof NaN === ‘Number’ typeof NaN == ‘Number’

(2) Q: JS implicit conversion, display conversion

ValueOf is called first for non-base types, and toString is called if valueOf fails to return a valueOf the base type

Strings and numbers

  • The “+” operator, if one of them is a string, is converted to a string and string concatenation is performed
  • The “-” operator, conversion to a number, and subtraction (-a, a * 1 a/1) are all implicitly cast
[] + {} and {} + []Copy the code

Boolean value to the number

  • 1 + true = 2
  • 1 + false = 1

Convert to a Boolean value

  • The second one in for
  • while
  • if
  • Ternary expression
  • | | (logical or) && (logical) and the left operand

symbol

  • Cannot be converted to a number
  • Can be converted to a Boolean value (both true)
  • Can be converted to the string “Symbol(cool)”

Loose equality and strict equality

Loose equality allows casting, while strict equality does not

Strings and Numbers

Convert to a number and compare

Other types and Boolean types

  • The Boolean is converted to a number and the comparison continues

Objects and non-objects

  • Execute the ToPrimitive(object) of the object and continue the comparison

False value list

  • undefined
  • null
  • false
  • +0, -0, NaN
  • “”

Q: What do you mean by this, bind, call, apply

They’re all methods of functions

call: Array.prototype.call(this, args1, args2]) apply: Array.prototype.apply(this, [args1, args2]) : foo. Appy (null, []) : foo. The operator

  • New Binding > Show Binding > Implicit Binding > Default binding
  • If you need to use Bind’s currying and Apply’s array deconstructing to bind to null, create a DMZ Object using object.create (NULL) whenever possible

Four rules:

  • The default binding, which has no other modifications (bind, apply, call), is defined to point to a global object in non-strict mode and to undefined in strict mode
function foo() {
 	console.log(this.a); 
}

var a = 2;
foo();
Copy the code
  • Implicit binding: If the call location has a context object or is owned or contained by an object, then the implicit binding rule binds this in a function call to that context object. Furthermore, only the upper or last level of the chain of object properties plays a role in the call location
function foo() {
  console.log(this.a);
}

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

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

var obj = {
  a: 2
};

foo.call(obj);
Copy the code

Shows 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);
Copy the code

New binding. The New call to the function creates a New object and binds it to the this call.

  • When New is bound, if it’s New and it’s a hard bound function, then it replaces the hard bound this with an object created by New,
function foo(a) {
  this.a = a;
}

var bar = new foo(2);
console.log(bar.a)
Copy the code

(4) Q: 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];
}
Copy the code
// apply

Function.prototype.apply = function (context, argsArr) {
  context = context || window;
  
  const fnSymbol = Symbol("fn");
  context[fnSymbol] = this; context[fnSymbol](... argsArr);delete context[fnSymbol];
}
Copy the code
// 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);deletecontext[fnSymbol]; }}Copy the code

(3) Q:setTimeout(fn, 0)How long to execute, Event Loop

The setTimeout is placed in the queue in order and then waits for the call stack to clear before it is executed. The order in which these operations are queued is determined by the set delay time

Handwritten question: Promise principle

class MyPromise {
  constructor(fn) {
    this.callbacks = [];
    this.state = "PENDING";
    this.value = null;

    fn(this._resolve.bind(this), this._reject.bind(this));
  }

  then(onFulfilled, onRejected) {
    return new MyPromise((resolve, reject) = >
      this._handle({
        onFulfilled: onFulfilled || null.onRejected: onRejected || null,
        resolve,
        reject,
      })
    );
  }

  catch(onRejected) {
    return this.then(null, onRejected);
  }

  _handle(callback) {
    if (this.state === "PENDING") {
      this.callbacks.push(callback);

      return;
    }

    let cb =
      this.state === "FULFILLED" ? callback.onFulfilled : callback.onRejected;
    if(! cb) { cb =this.state === "FULFILLED" ? callback.resolve : callback.reject;
      cb(this.value);

      return;
    }

    let ret;

    try {
      ret = cb(this.value);
      cb = this.state === "FULFILLED" ? callback.resolve : callback.reject;
    } catch (error) {
      ret = error;
      cb = callback.reject;
    } finally{ cb(ret); }}_resolve(value) {
    if (value && (typeof value === "object" || typeof value === "function")) {
      let then = value.then;

      if (typeof then === "function") {
        then.call(value, this._resolve.bind(this), this._reject.bind(this));

        return; }}this.state === "FULFILLED";
    this.value = value;
    this.callbacks.forEach((fn) = > this._handle(fn));
  }

  _reject(error) {
    this.state === "REJECTED";
    this.value = error;
    this.callbacks.forEach((fn) = > this._handle(fn)); }}const p1 = new Promise(function (resolve, reject) {
  setTimeout(() = > reject(new Error("fail")), 3000);
});

const p2 = new Promise(function (resolve, reject) {
  setTimeout(() = > resolve(p1), 1000);
});

p2.then((result) = > console.log(result)).catch((error) = > console.log(error));
      
Copy the code

Q: Js script loading problem, async, defer problem

  • Use Defer if you depend on other scripts and DOM results
  • Use async if you don’t have a strong dependency on DOM and other scripts

The resources

  • Mp.weixin.qq.com/s/pw5lfFeNa…

Q: How do I know if an object is empty?

Object.keys(obj).length === 0

Online programming, getUrlParams(URL,key); It’s simply a matter of getting a parameter to the URL, but consider boundary cases, multiple return values, and so on

<script SRC = ‘XXX’ ‘XXX’ /> <script SRC = ‘XXX’ ‘XXX’ />

Onload is executed after the load is complete

Q: How to add event listener, two kinds

The onclick and addEventListener

Q: Event propagation mechanism (event flow)

Bubble and capture

(4) Q: Talk about the prototype chain and its inheritance

  • All the normal [[Prototype]] chains eventually point to the built-in object.prototype, which contains many of the functionality common to JavaScript
  • Why is it possible to create “classes” with the help of a special property: all functions by default have a common, non-enumerable property called Prototype that points to another object, often called the function’s prototype
function Person(name) {
  this.name = name;
}

Person.prototype.constructor = Person
Copy the code
  • When a new constructor call occurs, the [[Prototype]] of the new object created is linked to the object pointed to by Person.prototype. This mechanism is called Prototype chain inheritance

  • Methods are defined on stereotypes, and properties are defined on constructors

  • First, let’s talk about the relationship between JS prototypes and instances: Each constructor has a prototype object that contains a pointer property to the constructor. The constructor call with new generates an instance that contains a pointer to the prototype object. [[Prototype]] links to the Prototype object

  • Then let’s talk about finding properties in JS: When we try to reference a property of an instance object, we look for it in this way: first, we look for the property on the instance object. If we can’t find it, we look for it on the object to which the constructor of the instance object points. If we can’t find it, we look for it on the object to which the constructor of the instance object points. Look up the prototype object of the constructor to which the prototype object points

  • What is a Prototype chain: such a hierarchical lookup resembles a chain and is linked by the [[Prototype]] property, so it is called a Prototype chain

  • What is prototype-chain inheritance, analog-class inheritance: When there are two constructors A and B, the process of linking the prototype-object of one constructor A to the prototype-object of another constructor B through its [[Prototype]] property is called prototype-inheritance.

The more correct interpretation of the standard answer

What is a prototype chain?

When an Object is looking for a property, if it is not found in itself, the Object will look for its own prototype. If it is not found, the Object will continue to look for its own prototype until it finds the Object. This upward lookup chain by linking through archetypes is called the archetype chain

What is prototype inheritance?

An object can use properties or methods of another object. This is called inheritance. Specifically, by setting the prototype of this object to another object, so according to the rules of the prototype chain, if you look for an object property that does not exist, you will look for another object, which is equivalent to an object can use the properties and methods of another object.

Refer to the link

  • zhuanlan.zhihu.com/p/35790971

Q: Say something about JS

Is a dynamic language based on archetypes. The main unique features are this, archetypes, and archetype chains.

JS is strictly divided into: language standard part (ECMAScript) + host environment part

Language standard section

ES6 was released in 2015, introducing a number of new features that made it possible to write large projects, and the standard has been code-named annually since 2015

Host environment part

  • The browser hosting environment includes DOM + BOM and so on
  • In Node, the host environment includes files, databases, networks, interactions with the operating system, and so on

Q: What functions can an array call?

  • push
  • pop
  • splice
  • slice
  • shift
  • unshift
  • sort
  • find
  • findIndex
  • Map/Filter/Reduce and other functional programming methods
  • There are also methods on the prototype chain: toString/valudOf

Q: How to determine the type of an array

Array.isArray

Q: Is arguments in the function an array? Class array to array method understand?

It’s array-like, it’s in the duck category, it looks like an array,

  • . The operator
  • Array.from
  • Array.prototype.slice.apply(arguments)

Q: Have you ever used TypeScript? What does it do?

Adding type support to JS, as well as providing support for the latest version of the ES syntax, is good for team collaboration and troubleshooting, developing large projects

Q: Has the PWA ever been used? How does serviceWorker work?

Progressive Web Applications (PWA) is a concept Google introduced in late 2015. It’s basically a Web application, but looks and feels like a native app. Pwa-enabled websites can provide functions such as offline work, push notifications, and access to device hardware.

A Service Worker is a script that the browser runs in the background independently of the web page, and it opens the door to features that don’t require web pages or user interaction. They now include features such as push notifications and background synchronization. In the future, Service workers will support other features such as periodic synchronization or geo-fencing. The core functionality discussed in this tutorial is the ability to intercept and process network requests, including programmatically managing responses in the cache.

Refer to the link

  • Juejin. Im/post / 5 e26aa…

Q: ES6 previously used Prototype to implement inheritance

Object.create() creates a “new” Object and then associates the [[Prototype]] inside that Object to the Object you specified (foo.prototype). Object.create(null) Creates an Object with an empty [[Prototype]] link. This Object cannot delegate.

function Foo(name) {
  this.name = name;
}

Foo.prototype.myName = function () {
  return this.name;
}

// Inherit attributes by borrowing constructor calls
function Bar(name, label) {
  Foo.call(this, name);
  this.label = label;
}

// Inherit the method and create the backup
Bar.prototype = Object.create(Foo.prototype);

// The correct constructor must be set, otherwise a type determination error will occur
Bar.prototype.constructor = Bar;

 // Must be after the previous step
Bar.prototype.myLabel = function () {
  return this.label;
}

var a = new Bar("a"."obj a");

a.myName(); // "a"
a.myLabel(); // "obj a"
Copy the code

Q: If a constructor binds an object, does the instance created by the constructor inherit the properties of the object? Why is that?

No inheritance, because according to the rules for this binding, the new binding takes precedence over the bind display binding. When a constructor call is made with new, a new object is created. This new object replaces bind’s object binding as this, and if the function returns no object, Returns the newly created object

(3) What’s the difference between an arrow function and an ordinary function? Can arrow functions be constructors?

  • Normal functions are defined by the function keyword, this cannot be used in conjunction with lexical scope, and is bound at runtime, depending only on how the function is called, where it is called, and where it is called. (Depends on the caller, and whether it runs independently)
  • The arrow function uses an operation called a “fat arrow.= >Definition: the arrow function does not apply the four rules of the normal this function binding. Instead, the outer (function or global) scope determines this, and the arrow function binding cannot be modified (nor can new).
    • Arrow functions are often used in callback functions, including event handlers or timers
    • The arrow function, and var self = this, both attempt to replace the traditional this mechanism by pulling the this binding back into lexical scope
    • No prototype, no this, no super, no arguments, no new.target
    • Cannot be called with the new keyword
      • There are two methods inside a function: [[Call]] and [[Construct]]. When a function is called with new, the [[Construct]] method is executed to create an instance object, and then the body of the function is executed to bind this to the instance object
      • When called directly, the [[Call]] method is executed, executing the body of the function directly
      • The arrow function has no [[Construct]] method, cannot be used as a constructor call, and will report an error when called with new.
function foo() {
  return (a) = > {
    console.log(this.a); }}var obj1 = {
  a: 2
}

var obj2 = {
  a: 3 
}

var bar = foo.call(obj1);
bar.call(obj2);
Copy the code

The resources

  • Segmentfault.com/a/119000001…

Q: Do you know the ES6 Class? The Static keyword

Add methods directly to the function object of the class, rather than to the prototype object of the function object

(3) Q: Event Loop mechanism

The Event Loop mechanism tells us the execution order of JavaScript code as a whole. An Event Loop is a browser or Node mechanism to solve the problem of JavaScript single thread running without blocking, which is often used in asynchronous principle.

The Script is executed, then the microtask queue is emptied, then the next event cycle is started, and the macro task is executed first, then the microtask queue is emptied, and so on.

  • Task: macro Script/setTimeout/setInterval/setImmediate/I/O/UI Rendering
  • Microtask: process.nexttick ()/Promise

The setTimeout and setInterval of the appeal are the source of the task, and the actual task that enters the task queue is the task that they distribute.

priority

  • SetTimeout = setInterval A queue
  • setTimeout > setImmediate 
  • process.nextTick > Promise
for (const macroTask of macroTaskQueue) {  
  handleMacroTask();    
  for (const microTask ofmicroTaskQueue) { handleMicroTask(microTask); }}Copy the code

Refer to the link

  • Juejin. Im/post / 59 e85e…

(2) Handwritten question: array flattening

function flatten(arr) {
  let result = [];

  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flatten(arr[i]));
    } else{ result = result.concat(arr[i]); }}return result;
}

const a = [1[2[3.4]]];
console.log(flatten(a));

Copy the code

Handwritten question: realize currie

Set some parameters beforehand

What is A corylization: A function that takes A and returns A new function that handles the rest of A’s arguments

function createCurry(func, args) {
  var argity = func.length;
  var args = args || [];
  
  return function () {
    var _args = [].slice.apply(arguments); args.push(... _args);if (args.length < argity) {
      return createCurry.call(this, func, args);
    }
    
    return func.apply(this, args); }}Copy the code

Handwritten question: array deduplicate

Array.from(new Set([1.1.2.2]))
Copy the code

Question: The let closure

Let creates a temporary dead zone. In the current execution context, the variable is promoted, but it is not initialized. Therefore, during the execution context execution phase, if the execution code has not yet executed the variable assignment, it will report an error that the variable is not initialized.

Q: Variable lift

When the function runs, it first creates the execution context, pushes the execution context onto the stack, and then runs the execution context when it is at the top of the stack.

Three things are done during the creation of an execution context: Create a variable object with a value of “arguments”; create a variable object with a value of “arguments”; create a variable object with a value of “function”; create a reference with a value of “function”; It will then scan the var variable declaration and create a property of the same name with the value undefined, which is the variable promotion.

How to use instance

The left-hand side can be any value, the right-hand side can only be a function

'hello tuture' instanceof String // false
Copy the code

The resources

  • Juejin. Im/post / 5 d79cc…
  • Mp.weixin.qq.com/s/pw5lfFeNa…
  • Mp.weixin.qq.com/s/bHclDpsGd…
  • www.jianshu.com/p/cd3fee40e…

❤️ Thanks for your support

If you like it, don’t forget to share it, like it and watch it again.