1. What are the data types of JS?

According to the way of variable type transfer in JavaScript, it can be divided into two categories: basic data type and reference data type. Basic data types include Undefined, Null, Boolean, Number, String, Symbol (new in ES6). There is only one reference data type, Object, which includes objects, arrays, and functions. The typeof operator is used to determine the data type, and there are two syntax:

typeof 123;/ / a grammar

const FG = 123;
typeof FG;2 / / grammar

typeof(null) / / return the object;
null= =undefined // Return true because undefined derives from null;
null= = =undefined // return false.
Copy the code


2. What is the difference between a base data type and a reference data type?

(1) When both are passed as parameters of the function: The basic data type is passed as a copy of the data, and the change of the original data will not affect the passed data. A reference data type is passed in the reference address of the data, and changes to the original data affect the incoming data. (2) Storage location in memory: Basic data types are stored on the stack. A reference data type stores a pointer in the stack to which the data entity is stored in the heap.

3. What are the methods for determining data types?

(1) use typeof to judge the typeof data; (2) A instanceof B can be used to determine whether A is an instanceof B, but it cannot detect null and undefined; (3) B. Constructor == A can judge whether A is the prototype of B, but constructor detection Object is different from Instanceof, and can also handle detection of basic data types.

However, the constructor of the function is unstable, which is mainly reflected in the rewriting of the class prototype. In the process of rewriting, it is possible to overwrite the previous constructor, which results in inaccurate detection.

(4) the Object. The prototype. ToString. Call ()

Object. The prototype. ToString. Call () is the most commonly used the most accurate way.


4. What is the difference between deep copy and deep copy? How to do that?

Shallow copies only Pointers to an object, not the object itself. Object.assign() : If the target Object has only one layer, it is a deep copy. (2) Extended operator; A deep copy is a copy of all reference structures of the data. The implementation of deep copy is as follows: (1) handwritten traversal recursive assignment; (2) Use json.parse () and json.stringify () together.

5. What’s the difference between let and const

Var, let, and const are all keywords used to declare variables or functions. The difference lies in:

var let const
scope Function scope Block-level scope Block-level scope
Scope declaration promotion There are None (Temporary dead zone) There is no
Whether the declaration can be repeated is no no
Whether the assignment is repeatable is is No (constant)
Whether an assignment is required during initialization no no is


6. What are execution context and execution stack?

The execution context of variables or functions determines how they behave and what data can be accessed. Each context has an associated variable object on which all variables and functions defined in that context reside (for example, the global context associated with the DOM is the Window object). Each function call has its own context. When the code execution stream enters a function, the context of the function is pushed onto an execution stack. After the function completes execution, the execution stack pops up the function context, and all variables and functions on it are destroyed, returning control to the previous execution context. The JS execution flow is controlled through this execution stack.


7. What are scopes and scope chains?

A scope can be thought of as a separate domain and can be thought of as the scope in which an identifier can be applied. The greatest use of a scope is to isolate variables. Variables of the same name in different scopes do not conflict. ES6 has three concepts of global scope, function scope and block-level scope. When a variable is not defined in the current block-level scope, it looks for the parent scope (the parent scope that created the function). If the parent is not found, it is searched up and down until the global scope is found. This layer by layer relationship is the scope chain.

8. What is the difference between scope and execution context?

(1) The execution context of a function is generated only when the function is called, and its scope is generated when the function is created; (2) The scope of a function may contain several execution contexts (possibly zero, when the function is not called).

9. What does this refer to in each case?

The reference to this can only be determined at call time because this is part of the execution context. (1) A function in the global scope whose internal this refers to the window:

var a = 1;
function fn(){
  console.log(this.a)
}
fn() / / output 1
Copy the code

(2) The function inside the object: its internal this refers to the object itself:

var a = 1;
var obj = {
  a:2.fn:function(){
  	console.log(this.a)
	}
}

obj.fn() 2 / / output
Copy the code

(3) Constructor: its internal this refers to the generated instance:

function createP(name,age){
	this.name = name / / this. The name to point P
  this.age = age / / this. The age to point P
}
var p = new createP("老李".46)
Copy the code

(4) Apply, call, bind: this refers to the first argument:

function add(c,d){
	return this.a + this.b + c + d
}
var o = {a:1.b:2)
add.call(o,5.7) / / output 15
Copy the code

(5) Arrow function: Arrow function does not have its own this, check whether the outer function has a function, if so, this is the inner arrow function this, if not, this is the window.

10. How do I change the pointer to this?

You can use the apply, call, and bind methods to change this (without changing the scope of the function). (1) The first parameter of this is the object to which this refers, that is, the context to which the function is called (if not, it refers to the global window). (2) The second argument to apply is an array or array-like object. Bind and call take multiple arguments separated by commas. (3) Apply and call only make changes to the original function, and bind returns the new function (which needs to be called again to take effect).

    console.log(Math.max.apply(null[1.2.3])) / / - 3 apply output
    console.log(Math.max.apply(null.new Array(1.2.3))) / / - 3 apply output

    console.log(Math.max.call(null.1.2.3)) / / output 3 - call

    console.log(Math.max.bind(null.1.2.3) ())/ / output 3 -- bind
Copy the code

What is a closure?

A closure is a function that references variables in the scope of another function, and this pattern is usually implemented in a function nested structure. The inside function can access the variables of the outside function, and the outside variables are part of the inside function. Closures have the following functions: (1) enhance encapsulation, simulate the implementation of private variables; (2) Implementation of resident memory variables.

Closures should not be abused because they can leak memory and affect web page performance. Immediately after the closure is used, the resource is freed and the reference variable is pointed to NULL.


12. What is a prototype, prototype chain?

Prototype: When JS declares a constructor (a function used to instantiate an object), it creates a corresponding object in memory that is the prototype of the original function. By default, the constructor has a prototype property whose value points to the function’s prototype. The stereotype also has a constructor property, whose value points to the original function. An object instantiated by a constructor does not have a prototype property. By default, it has a __proto__ property, whose value refers to the constructor’s prototype object. Properties added or modified on the prototype object are shared across all instantiated objects.

When accessing an attribute in an instantiated Object, it will first look inside the Object. If it can’t find it, it will look for the prototype to which its __proto__ points. If it still can’t find it, it will continue to look for the parent prototype to which its __proto__ points until it finds or object. prototype. This chain process is called prototype chain.


13. What is anti-vibration and throttling? How to do that?

Anti – shake and throttling are solutions to prevent high – frequency triggering events in a short period of time. The principle of anti-shake is that if an event is executed several times within a certain period of time, only the last one is executed. Throttling works by saying that events to be executed are periodically cooled and cannot be executed. The application scenarios are as follows: Search box Real-time search, scrolling to change related events.

//@fn: the function to execute
//@delay: set time limit

// The buffeting function
function debunce(fn,delay){
	let flag = null;
  return function(){
  	if(flag) clearTimeout(flag)
    // Use apply to change the function pointing so that the encapsulated function can receive the event itself
    flag = setTimeout(() = >fn.apply(this.arguments),delay)
  }
}

// throttling function
function throttle(fn,delay){
	let flag = true;
  return function(){
  	if(! flag)return false;
    flag = false;
    setTimeout(() = >{
      fn.apply(this.arguments)
      flag=true
    },delay)
  }
}
Copy the code

14. How to understand synchronous and asynchronous?

Synchronization: A pattern in which processing instructions are executed one by one in the order in which the code is written, so that the next code can be executed only after the previous code has been executed. Asynchrony: Can be understood as a way of parallel processing where other tasks can be performed without waiting for a program to complete.

The reason why JS needs to be asynchronous is because JS runs in a single thread. Common asynchronous scenarios include timers, Ajax requests, and event bindings.


15. How is JS implemented asynchronously?

The JS engine is single threaded, but asynchronous because of the event loop and task queue system. Event loop: JS creates a loop similar to while (true), each time the loop body is executed, it is called a Tick. The Tick process is to check whether there are any pending events, and if there are, the relevant events and the callback function are put into the execution stack and executed by the main thread. Events to be processed are stored in a task queue. That is, each Tick checks whether there are tasks to be executed in the task queue. Task queue: Asynchronous operations add related callbacks to the task queue. Different asynchronous operations are added to the task queue at different times, such as onclick, setTimeout, and Ajax processing. These asynchronous operations are performed by webcore in the browser kernel, which contains three webapis. These are DOM Binding, Network, and Timer modules. Onclick is handled by the DOM Binding module, and when the event is triggered, the callback function is immediately added to the task queue. SetTimeout is handled by the timer module for delay. When the time reaches, the callback function will be added to the task queue. Ajax is handled by the Network module and the callback is added to the task queue after the network request has completed and returned. Main thread: JS has only one thread, called the main thread. The event loop, on the other hand, starts execution after the code in the execution stack in the main thread has finished executing. As a result, the code to execute in the main thread takes too long, blocking the execution of the event loop and thus the execution of the asynchronous operation. Only when the execution stack in the main thread is empty (that is, after the synchronous code has finished executing) does the event loop observe the event callback to be executed. When the event loop detects an event in the task queue, it pulls the related callback into the execution stack for the main thread to execute.

16. What is AJAX? How to do that?

Ajax is a technique that enables partial web page refreshes and asynchronously refreshes web pages. Ajax implementation mainly includes four steps: (1) to create the core object XMLhttpRequest; (2) Use the open method to open the connection with the server; (3) Use the send method to send requests; (“POST” request, also need to set the request header) (4) listen to the server response, receive the return value.

//1- Create a core object
// This object has compatibility issues and should be used with ActiveXObject in earlier versions of browsers
const xthhp = new XMLHttpRequest();
//2- Connect to the server
//open(method,url,async)
xhttp.open("POST"."http://localhost:3000".true)
// Set the request header
xmlHttp.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");//3- Send the request
// The send method sends request parameters. For example, the GET method concatenates the URL after the open method
xhttp.send({_id:123})
//4- Receives the server response
// the onreadyStatechange event, which is automatically called when the XHTTP state changes
xhttp.onreadystatechange =function(){
  There are five status codes: 0- Not open 1- Open 2- Send 3- Read response 4- Read response complete
  if(xhttp.readyState == 4 && xhttp.status == 200){
  	alert("Ajax request completed")}}Copy the code

17. What are the ways to achieve asynchrony?

(1) Callback function mode: the function that needs to be executed asynchronously is executed as callback function. Its disadvantage is that it will cause callback hell (too many nested callback layers and chaotic code structure) when processing complex asynchronous logic. (2) Event monitoring mode: using the idea of event-driven, when an event occurs to trigger the execution of asynchronous functions, its disadvantage is that the whole code has to be changed into event-driven mode, it is difficult to distinguish the main process; (3) Publish and subscribe mode: when the asynchronous task is completed, the message is published to the signal center, and other tasks subscribe the message in the signal center to determine whether they start to execute; (4) Promise(ES6) : There are three states of Promise object: Pending, successful and rejected. (5) Async /await(ES7) : asynchronous function implemented based on Promise; (6) Use generator implementation.

18. What do you mean by Promise?

The Promise object has the following two characteristics: (1) the state of the object is not affected by the outside world. The Promise object has three states: Pending, depressing, and Rejected. The value of the state is determined only by the asynchronous result and cannot be changed by any other operation. (2) Once the state is formed, it does not change and can be obtained at any time. The status will change from Pending to regret or Rejected, which is resolved.

The disadvantages of Promise are as follows: (1) Once a Promise is implemented, it cannot be cancelled; (2) The callback function cannot be set, and its internal errors cannot be caught; (3) When it is in the pending state, it is impossible to know the specific development stage.

The commonly used methods in Pomise are: (1) promise.prototype. then() : when the state of the Promise instance changes, the callback function inside the THEN will be called. The then method takes two arguments (‘ Resolved ‘and’ rejected ‘) (2) promise.prototype. Catch () : An alias at. Then (null, Rejection) or. Then (undefined, Rejection) that specifies the callback when an error occurs.

19. How to understand macro task and micro task??

Macro tasks include: Script (overall code), setTimeout, setInterval, I/O, page rendering; Microtasks include promise. then, Object.observe, and MutationObserver. The execution order is roughly as follows: main thread task — > macro task — > micro task — > macro task in micro task — >……. — > Until the task is complete

20. What is cross-domain? How to solve cross-domain problems?

< link href=XXX>

/ / app. Set in js
var app = express();

/ / CORS cross-domain -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
// CORS: set to allow cross-domain middleware
var allowCrossDomain = function (req, res, next) {
  // Set the URL to allow cross-domain access (* indicates that arbitrary URL access is allowed)
  res.header("Access-Control-Allow-Origin"."*");
  // Set the request header that allows cross-domain access
  res.header("Access-Control-Allow-Headers"."X-Requested-With,Origin,Content-Type,Accept,Authorization");
  // Set the request type to allow cross-domain access
  res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
  // Set the server to accept cookies
  res.header('Access-Control-Allow-Credentials'.'true');
  next();
};
app.use(allowCrossDomain);
//------------------------------------------------------------------------------------
Copy the code

(3) Principle of Node middleware proxy: The same-origin policy is only the policy that browsers need to follow, so middleware server is built to forward requests and responses to achieve cross-domain purposes.

/* server1.js proxy server (http://localhost:3000)*/
const http = require('http')

// Step 1: Accept the client request
const server = http.createServer((request, response) = > {
  
// Proxy server, directly interact with the browser, need to set the CORS header field
  response.writeHead(200, {'Access-Control-Allow-Origin':The '*'.'Access-Control-Allow-Methods':The '*'.'Access-Control-Allow-Headers':'Content-Type'  
	})
  
// Step 2: Forward the request to the server
	const proxyRequest = http.request({
        host:'127.0.0.1'.port:4000.url:'/'.method:request.method,
        headers:request.headers      
	},
  serverResponse= >{
   // Step 3: Receive a response from the server
        var body = ' '
        serverResponse.on('data'.chunk= >{
          body += chunk        
				})
        serverResponse.on('end'.() = > {
          console.log('The data is '+ body)
          
// Step 4: Forward the response to the browser
          response.end(body)      
				})     
	})
  .end()
  })

server.listen(3000.() = >{console.log('Middleware server address: http://localhost:3000')})


// server2.js(http://localhost:4000)
const http = require("http");
const data = { title: "fontend".password: "123456" };
const server = http.createServer((request, response) = > {
    if (request.url === "/") {
        response.end(JSON.stringify(data)); }}); server.listen(4000.() = > {
    console.log("The server is running at http://localhost:4000");
});
Copy the code

(4) Principle of Nginx reverse proxy: Similar to Node middleware server, through nginx proxy server. Implementation method: download and install nginx, modify the configuration.

21. What are the methods to implement inheritance?

(1) Class extends extends (ES6)

/ / class template
class Animal {
  constructor(name){
    this.name = name
  }
}
/ / a derived class
class Cat extends Animal{/ / the point. Extends method internally using constructor+super
  constructor(name) {
    super(name);
    // when called as a function, super represents the constructor of the parent class
  }/ / constructor can be omitted
  eat(){
    console.log("eating")}}Copy the code

(2) Prototype inheritance

/ / class template
function Animal(name) {
  this.name = name; 
}
// Add a prototype method
Animal.prototype.eat = function(){
  console.log("eating")}function Cat(furColor){ 
   this.color = color ;
};
/ / a derived class
Cat.prototype = new Animal()// Important: The prototype of the subinstance is equal to the instance of the parent class
Copy the code

(3) Borrow constructor inheritance

function Animal(name){
	this.name = name
}
function Cat(){
	Animal.call(this."CatName")// Call the parent class's call method
}
Copy the code

(4) Parasitic combinatorial inheritance (emphasis)

22. DOM event model and event flow?

The DOM event model includes event capture (top-down firing) and event bubbling (bottom-up firing, which is what Ie uses) mechanisms. Event broker can be done based on the event bubbling mechanism.

Event capture

The event bubbling



DOM event flow consists of three phases: event capture phase, target phase, and event bubbling phase.

What is an EventLoop?

Js is a single-threaded requirement, and its asynchronous operations are done through event loops. The whole event cycle consists of execution stack, message queue and microtask queue. Synchronized code calls execution directly on the execution stack. Callbacks in timers are pushed into the stack when the stack is empty and timed to complete. The callback of the promise and async asynchronous functions is pushed into the microtask queue and executed as soon as the execution stack is cleared and the asynchronous operation completes.

24. require/importThe difference between?

(1) require is CommonJS syntax, import is ES6 syntax; (2) require is only supported on backend servers. Import is supported in older browsers and nodes. (3) require imports a copy of the original exported value; import imports a reference to the exported value; (4) require is dynamically loaded when run, import is statically compiled; (5) require is not called in strict mode by default, import is called in strict mode by default.

Front End Interview Guide series portal:

Summary of Vue interview questions in the Front-end Interview Guide

Summary of HTML interview questions in the front-end Interview Guide

Front-end interview Guide CSS interview questions summary