Most Common Javascript Interview Questions and Answers in 2021

Js interview questions and answers (recommended collection, interview must pass!)

What happened between entering the URL and displaying the page?

  1. The user enters the url and presses Enter
  2. The browser process checks the url, assembles the protocol, and forms a complete url
  3. The browser process sends the url request to the network process through inter-process communication (IPC)
  4. After the network process receives the url request, it checks whether the local cache has cached the requested resource, and if so, returns the resource to the browser process
  5. If not, the network process initiates an http request (network request) to the web server
  6. The network process parses the response process. If it is 200, check the response type Content-Type. If it is a byte stream type, submit the request to the download manager. The navigation process is over and will not proceed; if it is html, notify the browser Process ready to render Process ready to render
  7. Prepare the rendering process; the browser process checks whether the current url is the same as the root domain name of the previously opened rendering process. If they are the same, the original process will be reused. If they are different, a new rendering process will be started;
  8. Transfer data, update status

(Click on How does the browser work? Interview question 1: From entering the URL to displaying the page, what happened in the middle? You can view the detailed explanation)

JavaScript data types and their detection?

Js data types are divided into two types:

  • Basic data types ; including Undefined, Null, Boolean, Number, String, Symbol (new in ES6, representing a unique value)
  • Reference data type ; can be collectively referred to as Object objects, including Object, Array and Function, etc.

Detection method:

  • typeof ; typeof returns a string representing the data type, and the returned results include: number, boolean, string, symbol, object, undefined, function and other 7 data types, but cannot judge null, array, etc.; (generally judge basic data types)
  • instanceof ; instanceof is used to judge whether A is an instance of B; (generally judge the reference data type)
  • Object.prototype.toString.call() (can judge all data types, the most accurate and common way)

What is the difference between typeof and instanceof?

typeof:

  • It is used to judge the basic data type, but typeof null returns Object. This is just a long-standing bug in JavaScript. It does not mean that null is a reference data type, and null itself is not an object.
  • Reference type data, if judged by typeof, except function will be recognized, the rest will output object

instanceof:

  • The instanceof operator is used to detect whether the prototype property of the constructor appears on the prototype chain of an instance object
  • Mainly detect reference data types, and return false for basic types;

the difference:

  • typeof returns the basic type of a variable, instanceof returns a boolean value
  • instanceof can accurately judge complex reference data types, but cannot correctly judge basic data types
  • And typeof also has disadvantages. Although it can judge the basic data type (except null), it cannot judge other reference data types except the function type.
  • If you need a general detection data type, you can use Object.prototype.toString, call this method, and uniformly return a string in the format “[object Xxx]”

Do you know the difference between stack and heap memory?

Stack memory:

  • The stack is the call stack we mentioned repeatedly before, and it is used to store the execution context.
  • The stack space will not be set too large, the stack is mainly used to save the address of the basic value and reference type value
  • The relatively fixed-size memory space allocated automatically has fast data reading and writing speed, but the storage content is small, and the system will automatically clean up and release variables once they are not used;

Heap memory:

  • Used to save a set of unordered and unique reference type values, which can be obtained by using the key name in the stack
  • The reading and writing speed of the heap is slow, but it stores a lot of content. Generally, objects are stored in the heap, and the size of the stored data is unknown in this respect.
  • The heap is dynamically allocated memory, the size is variable and will not be released automatically.

The difference between the two:

  • The difference in space allocation : the stack is automatically allocated and released by the operating system (compiler), and stores function parameter values, local variable values, etc. It operates like a stack in a data structure. The heap (operating system) is generally allocated and released by the programmer. If the programmer does not release it, it may be reclaimed by the OS at the end of the program. The allocation method is similar to a linked list.
  • Differences in cache methods : The stack uses a first-level cache, which is usually stored in the storage space when called, and released immediately after the call. The heap is stored in the second-level cache, and its life cycle is determined by the garbage collection algorithm of the virtual machine (it cannot be recycled once it becomes an orphan object). So the speed of calling these objects is relatively low.
  • Data structure difference : Heap can be regarded as a tree, such as: heap sorting. A stack is a first-in, last-out data structure.
  • The difference between storage types : the stack is generally used to save the address of the basic value and reference type value; the heap is used to save a group of unordered and unique reference type objects

Click on the working principle and practice of the browser - stack space and heap space to view the detailed explanation

What is the difference between deep copy and shallow copy?

shallow copy:

Creates a new object, which does not point to the same address, but which has an exact copy of the original object's property values. That is, the shallow copy of the object will only copy the "main" object, and the value of the basic type of the object attribute is copied. If the attribute is a reference type, the memory address is copied, and the copy is not deep, so it is called shallow copy;

  • Modifying the non-object reference class attributes of the first layer of the shallow copy object will not affect the original object
  • Since the shallow copy will not copy the object inside the object, the "inside object" will share the memory with the original object, so modifying the properties in the sub-property object of the shallow copy object will also affect the original object

Deep copy:

Deep copy not only copies each attribute of the meta object one by one, but also recursively copies the object attributes contained in each attribute of the original object to the new object at one time, so modifying the copied object will not affect the original object;

  • Deep copy is to copy each attribute of the object layer by layer, modifying any attribute of the copied object will not affect the original object

the difference:

Whether it points to the same object as the original data The first layer of data is the basic data type Subobjects contained in the original data
shallow copy no will not change the original data together will change the original data together
deep copy no will not change the original data together will not change the original data together

Click on the exploration and detailed explanation of shallow copy and deep copy in Javscript to view the detailed explanation

What are the commonly used methods to implement deep and shallow copy in the project?

The method of implementing shallow copy:

  • simple assignment
  • Shallow copy using for...in loop
  • Using the Object.assign() method

The method of implementing deep copy:

  • Implement deep copy using recursion
  • Implement deep copy through JSON object
  • slice(), concat() deep copy the array

Click on the exploration and detailed explanation of shallow copy and deep copy in Javscript to view the detailed explanation

What is the difference between assignment, shallow copy and deep copy?

Whether it points to the same object as the original data The first layer of data is the basic data type Subobjects contained in the original data
assignment yes will change the original data together will change the original data together
shallow copy no will not change the original data together will change the original data together
deep copy no will not change the original data together will not change the original data together

The memory map of the three:

assignment
insert image description here

shallow copy
insert image description here

Deep copyClick
insert image description here
to explore and explain the shallow copy and deep copy in JavscriptView detailed explanation

What does new do when it creates an object?

  1. First an empty object obj is created
  2. Connect objects and constructors through the prototype chain
  3. Bind this in the constructor to the newly created object obj
  4. Judging based on the return type of the constructor, if it is a primitive value, it will be ignored, if it is a return object, it needs to be processed normally

Do you understand the prototype and prototype chain in Javascript?

prototype:

  • In JavaScript, whenever an object is defined, it contains some predefined properties. Each function object has a prototype attribute, which points to the prototype object of the function.
  • Prototype objects will automatically obtain a constructor attribute, which is a pointer to the function where the prototype attribute is located;
  • When the constructor is called to create a new instance, the high-instance object will contain a pointer (internal attribute _proto_), pointing to the prototype object of the constructor;
  • The purpose of a prototype object is to contain properties and methods that can be shared by all instances of a particular type.

Prototype chain:

  • The prototype chain is that when an instance object is searching for an attribute, if it cannot be found, it will search along the __proto__ on the prototype associated with the object, and return if it is found. If it cannot be found, it will find the prototype of the prototype until it is searched. To the prototype of the topmost Object function, the _proto__ of its prototype object has no upper-level prototype that can point to, so its value is null and returns undefind;
  • Prototype chain is the main method to realize inheritance. The basic idea is to use prototype to let a reference type inherit the properties and methods of another reference type;

Click on the exploration and detailed explanation of prototypes and prototype chains in Javascript to view detailed explanations

Talk about inheritance in Javascript, how to implement inheritance?

What is inheritance:

Inheritance (inheritance) is a concept in object-oriented software technology; if a class B "inherits" from another class A, call this B a "subclass of A", and call A a "parent class of B". "It can also be said that "A is a superclass of B";

  • Inheritance allows subclasses to have various properties and methods of the parent class without writing the same code again
  • While the subclass inherits the parent class, it can redefine some properties and rewrite some methods, that is, overwrite the original properties and methods of the parent class, so that it can obtain different functions from the parent class

The way to implement inheritance:

  • Prototype chain inheritance
  • Constructor inheritance (with call)
  • Composition inheritance
  • prototypal inheritance
  • parasitic inheritance
  • parasitic compositional inheritance

Click on the inheritance and implementation methods in Javascript to view the detailed explanation

What is the execution context and execution stack in Javascript?

Execution context:

Execution context is an abstract concept of Javascript code execution environment. As long as Javascript code runs, it must run in the execution context;

There are three types of execution contexts:

  • Global execution context: only one, the global object in the browser is the window object, this points to this global object
  • Function execution context: there are countless, only created when the function is called, each time a function is called, a new execution context is created
  • Eval function execution context: refers to the code running in the eval function, which is rarely used and not recommended

Execution stack:

The execution stack, also called the call stack, has a LIFO (last-in-first-out) structure for storing all execution contexts created during code execution;

When the Javascript engine starts executing your first line of script code, it creates a global execution context and pushes it onto the execution stack

Whenever the engine encounters a function, it creates a function execution context and then pushes this execution context onto the execution stack

The engine will execute the execution context (usually the function execution context) at the top of the execution stack. When the function execution ends, the corresponding execution context will be popped up, and then the control flow will reach the next execution context of the execution stack.

Click JavaScript Execution Mechanism - Call Stack View Details

Tell me about your understanding of Javascript scope?

Scope refers to the area in the program where variables are defined, and this location determines the lifetime of the variable. In layman's terms, scope is the accessible scope of variables and functions, that is, scope controls the visibility and life cycle of variables and functions.

Before ES6, ES had only two scopes: global scope and function scope.

  • Objects in the global scope can be accessed anywhere in the code, and its life cycle is accompanied by the life cycle of the page.
  • Function scope is the variable or function defined inside the function, and the defined variable or function can only be accessed inside the function. After the function execution ends, the variables defined inside the function will be destroyed.

ES6 has block-level scope. Block-level scope is a piece of code wrapped in a pair of braces, such as functions, judgment statements, loop statements, and even a single {} can be regarded as a block-level scope.

Tell me about your understanding of closures and usage scenarios?

In JavaScript, according to the rules of lexical scope, internal functions can always access the variables declared in their external functions. When an internal function is returned by calling an external function, even if the external function has been executed, the internal function reference The variables of the outer function are still stored in memory, and we call the collection of these variables a closure.

If the closure is used incorrectly, it will easily cause a memory leak, so when using the closure, you should try to pay attention to a principle: if the closure will be used all the time, then it can exist as a global variable; but if the frequency of use If it is not high and takes up a lot of memory, try to make it a local variable.

Any closure usage scenario is inseparable from these two points:

  • create private variable
  • Extend the lifetime of variables

Scenes:

  • curried function

Click on the execution mechanism of JavaScript - scope chain and closure to view the details

Tell me about your understanding of the this object in Javascript?

  1. When the function is executed, first check whether there is a "." in front of the function name. If there is, whoever is in front of the ".", this is who; if not, this is window
  2. this in the self-executing function is always window
  3. In the constructor mode, this.xxx=xxx that appears in the class (in the function body) is an instance of the current class
  4. call, apply and bind can change the direction of this, which is the first parameter of the function
  5. The this of the arrow function depends on whether there is a function in the outer layer. If there is, the this of the outer function is the this of the inner arrow function. If not, this is the window.

What are the common methods of Javascript arrays?

Operation method:

  • 增:push()、unshift()、splice()、concat()
  • Delete: pop(), shift(), splice(), slice()
  • Change: splice()
  • 查:indexOf()、includes()、find()

Sort method:

  • The array itself has two methods: reverse(), sort()
  • Define sorting functions: bubble sort, insertion sort, merge sort, counting sort

Conversion method:

  • join()

Iteration method:

  • some()
  • every()
  • forEach()
  • filter()
  • map()

Click on the most commonly used method in the Javscript array (recommended collection) to view the detailed explanation

Write an array sorting method by hand?

Bubble Sort:

var arr = [3,4,1,2,21,5,15,6,63];
function BubbleSort(ary){
    
    
    for(var i = 0;  i < ary.length - 1;  i++){
    
    
        for(var j = i + 1;  j < ary.length;  j++){
    
    
            var current = ary[i];
            if(current > ary[j]){
    
    
                var tmp = ary[j];
                ary[j] = current;
                ary[i] = tmp;
             }
         }
    }
   return ary;
}
1
BubbleSort(arr); // [1, 2, 3, 4, 5, 6, 15, 21, 63]

Click on the most commonly used method in the Javscript array (recommended collection) to view the detailed explanation

What are the common methods of Javascript strings?

Operation method:

  • Added: concat(),
  • 删:slice()、substr()、substring()
  • 改:trim()、trimLeft()、trimRight()、repeat()、toLowerCase()、 toUpperCase()
  • 查:chatAt()、indexOf()、startWith()、includes()

Conversion method:

  • split

Template matching method:

  • match()
  • search()
  • replace()

Click on the common methods of Javascript strings to view detailed explanations

Talk about the type conversion mechanism in Javascript?

Common type conversions are:

  • cast (display conversion)
  • automatic conversion (implicit conversion)

Click on the six data types, mandatory type conversion and implicit type conversion of js to view the detailed explanation

What is the difference and usage scenario between == and ===?

Equal operator:

The equal operator is represented by two equal signs (==), and if the operands are equal, it will return true; the
equal operator (==) will first perform type conversion in the comparison, and then determine whether the operands are equal;

  • Both are simple types, strings and Boolean values ​​will be converted to numeric values, and then compared
  • Simple types are compared with reference types, the object is converted to a value of its original type, and then compared
  • Both are reference types, compare whether they point to the same object
  • null and undefined are equal
  • Returns false if NaN exists

Congruent operators:

The identity operator is represented by three equals signs ( === ), and returns true only if the two operands are equal without conversion. That is, the same type, the value must also be the same

the difference:

  • The equality operator (==) will do type conversion, and then compare the values, and the equality operator will not do type conversion
  • Comparing null and undefined, the equality operator (==) is true, and congruence is false

Except when the property of the comparison object is null or undefined, we can use the equality operator ==, and it is recommended to use the congruence operator === in other cases;

How to understand the event model in Javascript?

Event models can be divided into three types:

  • Primitive event model (DOM0 level)
  • Standard Event Model (DOM2 level)
  • IE event model (basically not used)

Click Event Model in Javascript to view details

Talk about your understanding of processes and threads?

Multithreading can process tasks in parallel, but a thread cannot exist alone, it is started and managed by a process.

A process is a running instance of a program. The detailed explanation is that when a program is started, the operating system will create a block of memory for the program to store code, running data, and a main thread for executing tasks. We call such an operating environment a process.

relation:

  • Any thread execution error in the process will cause the entire process to crash.
  • Data in the process is shared between threads.
  • When a process is closed, the operating system reclaims the memory occupied by the process.
  • The content between processes is isolated from each other.

Click on what is Event Loop? View details

Talk about the understanding of the event loop in Javascript?

JavaScript is single-threaded at the beginning of its design, which means that when the program is running, only one thread exists and can only do one thing at a time; in order to solve the problem of single-threaded running blocking, JavaScript uses an operating mechanism of the computer system, which This mechanism is called event loop (Event Loop)

In JavaScript, all tasks can be divided into:

  • Synchronous tasks: Tasks that are executed immediately. Generally, synchronous tasks will directly enter the main thread for execution
  • Asynchronous tasks: tasks executed asynchronously, such as ajax network requests, setTimeout timing functions, etc.

The running flowchart of synchronous task and asynchronous task is as follows:

insert image description here
From the above, we can see that the synchronous task enters the main thread, that is, the main execution stack, and the asynchronous task enters the task queue. After the task in the main thread is executed, it will be empty, and it will go to the task queue to read the corresponding task and push it into the main thread for execution. The continuous repetition of the above process is the event loop;

Click on the exploration and detailed explanation of the event loop mechanism in Javascript to view the detailed explanation

Introduce macrotasks and microtasks

insert image description here

Explain what is event proxy and application scenarios?

What is it:

Event proxy, in layman's terms, is to delegate the function of an element responding to an event (click, keydown...) to another element;

The event flow will go through three stages: capture stage -> target stage -> bubbling stage, and event delegation is completed in the bubbling stage;

Event delegation, which delegates the events of one or a group of elements to its parent layer or outer elements, the outer element is actually bound to the event, not the target element

When the event responds to the target element, it will trigger the binding event of its outer element through the event bubbling mechanism, and then execute the function on the outer element

Application scenario:

If we have a list with a large number of list items, we need to respond to an event when the list item is clicked. If a function is bound to each list item, it will consume a lot of memory. At this time, you can event delegate, bind the click event to the parent element ul, and then match the target element when the event is executed

Click Event Proxy and Application Scenarios to view details

What is function currying?

A technique that transforms a function that accepts multiple arguments into a function that accepts a single argument (the first argument of the original function) and returns a new function that accepts the remaining arguments and returns the result.

Convert a function that takes multiple arguments to a function that takes a single argument

// 普通函数
var add = function(x, y) {
    return x + y;
}    
add(3, 4)       //7var foo = 'bar';
// 柯里化
var foo = function(x) {
 return function(y) {
        return x + y
    }
}
foo(3)(4)       // 7  

What is the principle of Ajax and how to achieve it?

What is it:

The full name of AJAX (Async Javascript and XML)

That is, asynchronous JavaScript and XML are a web development technology for creating interactive web applications, which can exchange data with the server and update parts of the web page without reloading the entire web page

The principle of Ajax is simply to send an asynchronous request to the server through the XmlHttpRequest object, obtain data from the server, and then use JavaScript to manipulate the DOM to update the page

The flow chart is as follows:
insert image description here
Implementation process:

  • Create the core object of Ajax XMLHttpRequest object
  • Establish a connection with the server through the open() method of the XMLHttpRequest object
  • Build the data content required by the request and send it to the server through the send() method of the XMLHttpRequest object
  • Listen to your communication status on the server side through the onreadystatechange event provided by the XMLHttpRequest object
  • Accept and process the data results that the server responds to the client
  • Update the processing result to the HTML page

Click on the principle, implementation steps and packaging of Ajax to view the detailed explanation

What is the difference between bind, call and apply?

effect:

The functions of call, apply, and bind are to change the context when the function is executed, in short, to change the this point when the function is running;

the difference:

  • apply, call, and bind can change the this point of the function
  • Both apply and call change the point of the function this, and call and execute the function immediately after passing in the parameters
  • bind is to change the this point of the function and return a new function after passing in the parameters, and will not call and execute immediately
  • The parameters passed in by apply are in the form of an array; the parameters passed in by call are passed in one by one in order and separated by commas; the parameters passed in by bind can be in the form of an array or one by one in order.

Click the difference between bind, call and apply to view details

Tell me about your understanding of DOM, what are the common operations?

The full name of DOM is The Document Object Model, which is the document object model. It should be understood as a specification, a cross-platform, programming language-independent API, which treats HTML, XHTML or XML documents as a tree structure, and each node as an object, which can be used by programming languages Operations, which in turn change the structure of the document, are mapped to the display of the document.

To put it simply, DOM is for us to operate on documents such as HTML for the convenience of programming languages. Therefore, all nodes in HTML documents are regarded as individual objects, and then these objects form a tree according to the hierarchical relationship. This tree is Named DOM tree. With objects, programming is much more convenient. As long as you get the objects layer by layer, you can gracefully change the properties of the objects and dynamically change the display of documents such as HTML.

Let's analyze the common operations of DOM, which are mainly divided into:

  • create node
  • query node
  • update node
  • add node
  • delete node

Click on DOM understanding and common operations to view detailed explanations

Tell me about your understanding of BOM, what do you know about common BOM objects?

What is it:

BOM (Browser Object Model), the browser object model, provides objects that interact with the browser window independently of the content

Its function is to do some interactive effects with the browser, such as how to go back, forward, refresh the page, change the browser window, scroll the scroll bar, and obtain some customer information such as: browser brand version, screen resolution ;

BOM object:

  • window
  • location
  • navigator
  • screen
  • history

Click on the understanding of BOM and common BOM objects to view detailed explanations

Talk about several situations of memory leaks in JavaScript?

What is it :

Memory leak (Memory leak) is in computer science, due to negligence or error, the program fails to release memory that is no longer used;

For continuously running service processes, memory that is no longer used must be released in time. Otherwise, the memory usage will be higher and higher, which will affect the system performance in the slightest, and cause the process to crash in the worst case;

So most languages ​​provide automatic memory management to reduce the burden on programmers, which is called "garbage collection mechanism"

Common memory leaks:

  • unexpected global variable
  • Timers also often cause memory leaks
  • There are also closures, which prolong the life cycle of the internal variables of the function. Improper calling and untimely release will also cause memory leaks

What are the methods of local storage in JavaScript? Differences and application scenarios?

The way of local storage:

  • cookie
  • sessionStorage
  • sessionStorage

the difference:

  • Storage size: The cookie data size cannot exceed 4k. Although sessionStorage and localStorage also have storage size limitations, they are much larger than cookies and can reach 5M or greater
  • Effective time: localStorage stores persistent data, and the data will not be lost after the browser is closed unless the data is actively deleted; sessionStorage data is automatically deleted after the current browser window is closed; the cookie set by the cookie is valid until the expiration time of the cookie, even if the window or browser is closed
  • The interaction between data and server, the cookie data will be automatically transmitted to the server, and the server can also write cookies to the client; sessionStorage and localStorage will not automatically send data to the service

Application scenario:

  • To mark users and track user behavior, it is recommended to use cookies
  • Suitable for long-term storage of local data (tokens), it is recommended to use localStorage
  • One-time login for sensitive accounts, sessionStorage is recommended

Click on the local storage method to view the detailed explanation

How to implement function caching in JavaScript? What are the application scenarios?

What is it:

Function caching is to cache the results of function operations

In essence, it is to exchange space (cache storage) for time (calculation process)

A cache is simply a temporary data store that holds data so that future requests for that data can be processed more quickly

Implementation:

  • Closure
  • Currying
  • higher order functions

Caching is suitable for the following situations:

  • For expensive function calls, functions that perform complex calculations;
  • For functions with limited and highly repetitive input ranges
  • For recursive functions with repeated input values
  • For a pure function, that is, a function that returns the same output every time it is called with a specific input

Click How to implement function caching to view the details

Talk about function throttling and anti-shake? What's the difference? How to achieve?

Throttle:

  • Only run once within n seconds, if triggered repeatedly within n seconds, only one execution

Anti-shake (debounce):

  • The event is executed after n seconds, if it is triggered repeatedly within n seconds, the timer will be restarted

Vernacular comprehension:

The elevator completes a transportation, analogous to the execution and response of a function

Assuming that the elevator has two running strategies debounce (anti-shake) and throttle (throttle), the timeout is set to 15 seconds, regardless of the capacity limit

After the first person in the elevator comes in, it will be transported on time after 15 seconds, which is throttling;

After the first person enters the elevator, wait for 15 seconds. If someone comes in during the process, wait for 15 seconds to restart the timer until the delivery starts after 15 seconds, which is anti-shake

the difference:

Same point:

  • Both can be achieved by using setTimeout
  • The purpose is to reduce the frequency of callback execution. save computing resources

difference:

  • Function anti-shake, after a period of continuous operation, handle the callback, using clearTimeout and setTimeout to achieve. Function throttling, in a continuous operation, only executed once per period of time, used in high-frequency events to improve performance
  • Function anti-shake focuses on events that are triggered continuously for a certain period of time and is only executed once at the end, while function throttling is only executed once in a period of time

Click function throttling and anti-shake to view detailed explanation

What are the new features of es6?

  • Let and const keywords
  • Variable Destructuring Assignment
  • array, extension of object
  • arrow function
  • spread operator
  • class support
  • Function parameter default values
  • Simplified assignment of objects

Talk about the difference between var, let and const?

  • Variables declared by var have variable promotion, that is, the variable can be called before the declaration, and the value is undefined; let and const do not have variable promotion, that is, the variables they declare must be used after the declaration, otherwise an error will be reported
  • There is no temporary dead zone for var; there is a temporary dead zone for let and const, and the variable can only be acquired and used when the line of code that declares the variable appears
  • Var does not have block-level scope; let and const have block-level scope
  • var allows repeated declaration of variables; let and const do not allow repeated declarations of variables in the same scope
  • var and let can be modified; const declares a read-only constant. Once declared, the value of a constant cannot be changed

How do you understand promises in ES6 and usage scenarios?

Click to understand the promise in ES6 to view the detailed explanation

Guess you like

Origin blog.csdn.net/qq_44182284/article/details/116755897