Front end classic interview questions 60, with answers!

1, Short answer

1. What is anti shake and throttling? What's the difference? How?

Reference answer

Anti shake

After triggering the high-frequency event, the function will be executed only once in n seconds. If the high-frequency event is triggered again in n seconds, the time will be recalculated

  • Idea:

Each time an event is triggered, the previous deferred call method is cancelled

function debounce(fn) {
      let timeout = null; // Create a tag to store the return value of the timer
      return function () {
        clearTimeout(timeout); // Clear the previous setTimeout whenever the user enters
        timeout = setTimeout(() => { // Then create a new setTimeout to ensure that the fn function will not be executed if there are still characters in the interval after character input
          fn.apply(this, arguments);
        }, 500);
    function sayHi() {
      console.log('Anti shake successful');

    var inp = document.getElementById('inp');
    inp.addEventListener('input', debounce(sayHi)); // Anti shake


The high-frequency event is triggered, but it will only be executed once in n seconds, so throttling will dilute the execution frequency of the function

  • Idea:

Each time an event is triggered, judge whether there is a delay function waiting to be executed

function throttle(fn) {
      let canRun = true; // Save a tag through a closure
      return function () {
        if (!canRun) return; // Judge whether the flag is true at the beginning of the function. If it is not true, return
        canRun = false; // Set to false now
        setTimeout(() => { // Put the execution of the externally passed in function in setTimeout
          fn.apply(this, arguments);
          // Finally, after the setTimeout is executed, set the flag to true (key) to indicate that the next cycle can be executed. When the timer is not executed, the flag is always false and is return ed at the beginning
          canRun = true;
        }, 500);
    function sayHi(e) {
    window.addEventListener('resize', throttle(sayHi));

2. The misunderstanding of parameter length of get request and the difference between get and post request in cache

Myth: we often say that the size of get request parameters is limited, while the size of post request parameters is unlimited.

Reference answer

In fact, the HTTP protocol never specifies the request length limit for GET/POST. The restriction on get request parameters is that the source is the browser or web server, which limits the length of the url. In order to clarify this concept, we must emphasize the following points again:

  • The HTTP protocol does not specify the length limit of GET and POST
  • The maximum length of GET is displayed because browsers and web servers limit the length of URI s
  • Different browsers and WEB servers have different maximum lengths
  • To support IE, the maximum length is 2083byte s. If only Chrome is supported, the maximum length is 8182byte s

Add the difference between get and post in caching:

  • The get request is similar to the search process. The user can obtain data without connecting to the database every time, so the cache can be used.
  • Unlike post, post usually does modification and deletion, so it must interact with the database, so it cannot use cache. Therefore, get requests are suitable for request caching.

3. Modular development process

It can be considered from the perspectives of IIFE, AMD, CMD, CommonJS, UMD, webpack(require.ensure), ES Module, < script type = "module" > and so on.

Reference answer

Modularity is mainly used to extract public code, isolate scope, avoid variable conflict, etc.

IIFE: use self executing functions to write modularization. Features: execute code in a separate function scope to avoid variable conflict.

  return {

AMD: use requireJS to write modularization. Feature: dependencies must be declared in advance.

    // code is the content returned by index.js

CMD: use seaJS to write modularization. Feature: support the dynamic introduction of dependency files.

define(function(require, exports, module) {  
  var indexCode = require('./index.js');

CommonJS: the built-in modularity in nodejs.

var fs = require('fs');

UMD: compatible with AMD and CommonJS modular syntax.

webpack(require.ensure): Code segmentation in webpack version 2. X.

ES Modules: the modularity introduced by ES6 supports import to introduce another js.

import a from 'a';

4. npm module installation mechanism. Why can the corresponding module be installed automatically by entering npm install?

Reference answer

1. npm module installation mechanism:

  • Issue the npm install command

  • Query node_ Whether the specified module already exists in the modules directory

    • npm queries the registry for the URL of the module's compressed package
    • Download the compressed package and store it in the. npm directory under the root directory
    • Unzip the compressed package to the node of the current project_ Modules directory
    • If present, do not reinstall
    • If not

2. npm implementation principle

After entering the npm install command and pressing enter, you will go through the following stages (take npm 5.5.1 as an example):

1. Perform preinstall of the project itself

If the preinstall hook is defined for the current npm project, it will be executed at this time.

2. Determine the first layer dependent modules

The first thing to do is to determine the first layer dependencies in the project, that is, the modules directly specified in the dependencies and devdependences attributes (assuming that the npm install parameter is not added at this time).

The project itself is the root node of the whole dependency tree. Each first layer dependency module is a subtree under the root node. npm will start multiple processes to gradually find deeper nodes from each first layer dependency module.

3. Acquisition module

Module acquisition is a recursive process, which is divided into the following steps:

  • Get module information. Before downloading a module, you must first determine its version, because package.json is often a semantic Version (semver, semantic version). At this time, if the module information is available in the version description file (npm-shrinkwrap.json or package-lock.json), you can get it directly. If not, you can get it from the warehouse. If the version of a package in packageg.json is ^ 1.1.0, NPM will go to the warehouse to obtain the latest version in the form of 1.x.x.

  • Gets the module entity. In the previous step, the module's compressed packet address (resolved field) will be obtained. npm will use this address to check the local cache. If there is any in the cache, it will be taken directly. If not, it will be downloaded from the warehouse.

  • Find the module dependency. If there is a dependency, go back to step 1. If there is no dependency, stop.

4. Module flattening

What you got in the previous step is A complete dependency tree, which may contain A large number of duplicate modules. For example, module A depends on loadsh, and module B also depends on lodash. Before npm3, it will be installed in strict accordance with the dependency tree structure, which will cause module redundancy.

Starting from npm3, a dedupe process is added by default. It will traverse all nodes and place modules one by one under the root node, that is, the first layer of node modules. When duplicate modules are found, they are discarded.

Here, you need to define a duplicate module, which means that the module names are the same and semver compatible. Each semver corresponds to a version allowable range. If there is an intersection between the version allowable ranges of the two modules, you can get a compatible version without having to have the same version number, which can remove more redundant modules in the process of dedupe.

For example, if the foo module under node modules depends on lodash@^1.0.0 and the bar module depends on lodash@^1.1.0, ^ 1.1.0 is a compatible version.

When foo depends on lodash@^2.0.0 and bar depends on lodash@^1.1.0, there is no compatible version between them according to the rules of semver. A version will be placed on the node_ In modules, the other one remains in the dependency tree.

For example, suppose a dependency tree is originally like this:

-- foo
---- lodash@version1

-- bar
---- lodash@version2

Assuming that version1 and version2 are compatible versions, they will become the following form after dedupe:

-- foo

-- bar

-- lodash(Reserved Version (compatible version)

Assuming that version1 and version2 are incompatible versions, the following versions remain in the dependency tree:

-- foo
-- lodash@version1

-- bar
---- lodash@version2

5. Install the module

This step will update the node in the project_ Modules and execute the life cycle functions in the module (in the order of preinstall, install and postinstall).

6. Implement the project's own life cycle

If hooks are defined in the current npm project, they will be executed (in the order of install, postinstall, publish and prepare).

The last step is to generate or update the version description file, and the npm install process is completed.

5. What is the difference between ES5 inheritance and ES6 inheritance?

Reference answer

The inheritance of ES5 is implemented through the prototype or constructor mechanism. The essence of inheritance in ES5 is to create the instance object of the subclass first, and then add the method of the parent class to this (Parent.apply(this)).

The inheritance mechanism of ES6 is completely different. In essence, the instance object this of the parent class is created first (so the super() method of the parent class must be called first), and then the constructor of the child class is used to modify this.

Specifically: ES6 defines classes through the class keyword, which has construction methods. Classes inherit through the extends keyword. The subclass must call the super method in the constructor method, otherwise the new instance will be wrong. Because the subclass does not have its own this object, but inherits the this object of the parent class and processes it. If the super method is not called, the subclass cannot get the this object.

ps: Super keyword refers to the instance of the parent class, that is, the this object of the parent class. In the subclass constructor, you can use the this keyword after calling super, otherwise you will report it wrong.

6. Differences among setTimeout, Promise and async / wait

Reference answer:

Click to see the difference

7. The execution sequence or mechanism of the timer?

Reference answer

Because js is single threaded, when the browser encounters setTimeout or setInterval, it will first execute the current code block. Before that, it will push the timer into the browser's to be executed event queue. After the browser executes the current code, it will check whether there are tasks in the event queue. If so, it will execute the timer code.

Therefore, even if the timer time is set to 0, some current code will be executed first.

function test(){
    var aa = 0;
    var testSet = setInterval(function(){
  var testSet1 = setTimeout(function(){
  for(var i=0;i<10;i++){

Output results:

test //10 times

8. ['1', '2', '3'). What does map(parseInt) output and why?

Reference answer

Output: [1, NaN, NaN]

  • First, let's review the first parameter callback of the map function:

var new_array = callback(currentValue[, index[, array]]) { // Return element for new_array }[, thisArg])

This callback can receive a total of three parameters, of which the first parameter represents the currently processed element and the second parameter represents the index of the element.

  • parseInt is used to parse the string and make the string an integer with a specified cardinality.
    parseInt(string, radix)
    Two parameters are received. The first represents the processed value (string) and the second represents the cardinality at the time of parsing.
  • After understanding these two functions, we can simulate the operation
  1. When parseInt ('1 ', 0) / / radius is 0 and the string parameter does not start with "0x" and "0", it is processed based on 10. This time returns 1

  2. parseInt('2', 1) / / among the numbers represented by Radix 1 (hexadecimal), the maximum value is less than 2, so it cannot be parsed. NaN is returned

  3. parseInt('3', 2) / / among the numbers represented by Radix 2 (binary), the maximum value is less than 3, so it cannot be parsed. NaN is returned
    The map function returns an array, so the final result is [1, NaN, NaN]

9. What is the role of Doctype? How to distinguish between strict mode and hybrid mode? What do they mean?

Reference answer

Doctype is declared at the front of the document to tell the browser how to render the page. There are two modes, strict mode and hybrid mode.

  • Strict mode typesetting and JS operation mode run according to the highest standard supported by the browser.
  • Hybrid mode, backward compatibility, simulate old browsers, and prevent browsers from being compatible with pages.

10. The reason why the fetch sent the request twice

Reference answer

When a fetch sends a post request, it always sends it twice. The first time the status code is 204, and the second time it succeeds?

The reason is very simple, because when you use the post request of the fetch, the fetch sends an Options request for the first time, asking whether the server supports the modified request header. If the server supports it, the real request will be sent in the second time.

2, http, browser object

1. How does the client verify the validity of the certificate during HTTPS handshake

Reference answer

First, what is the HTTP protocol?

http protocol is a hypertext transport protocol, which is located in the application layer of tcp/ip four layer model; Communicating between the client and the server through request / response; However, it lacks security. The information transmission of http protocol is transmitted in clear text without any encryption, which is equivalent to running naked on the network; It is easy to be maliciously tampered with by middlemen, which is called middleman attack;

Encrypted communication:

For security, both parties can use symmetric encryption key to exchange information, but this symmetric encryption key will also be intercepted, which is not safe enough, and there is still a risk of being attacked by intermediaries;

So people came up with another way, using asymmetric encryption;

  • Encryption and decryption using public / private key; The communicating party A initiates the communication and carries its own public key, and the receiving Party B encrypts the symmetric secret key through the public key;

  • Then send it to initiator a; A decrypts through the private key;

  • The two transmitters then carry out encrypted communication through a symmetric secret key;

  • However, there will still be A kind of security in this way; Although the middleman does not know the private key of initiator A, he can steal heaven and earth and intercept the initiator's public key;

  • And send the public key of A pair of public / private keys generated by itself to B; Receiver B does not know that the public key has been changed secretly; According to the previous process, B encrypts the symmetric encryption key key2 generated by itself through the public key; Send to A;

  • This communication was intercepted by the middleman again. Although the latter communication still uses Key2, the middleman has mastered Key2; Easy encryption and decryption; There is still a risk of being attacked by intermediaries;

Solve the dilemma: the authoritative certification authority CA to solve it;

  • Making A certificate: as A server, A first sends its public key key1 to the certification authority and applies for A certificate from the certification authority;

  • The certification authority has its own set of public and private keys. CA encrypts key1 through its own private key, and generates A certificate signature through the server website and other information. The certificate signature is also encrypted by the authority's private key; After the production, the organization will issue the certificate to A;

  • Verify the authenticity of the certificate: when B sends A request communication to server A, A will no longer directly return its public key, but A certificate;

Note: all major browsers and operating systems have maintained the names and public keys of all authoritative certification authorities. B just need to know which authority issued the certificate and use the corresponding public key

Decrypt the certificate signature;

Next, B uses the same rules to generate its own certificate signature. If the two signatures are consistent, it indicates that the certificate is valid;

After the signature verification is successful, B can decrypt A's public key key1 by using the organization's public key again; The next operation is the same process as before;

Will the middleman intercept sending fake certificates to B?

Because the signature of the certificate is generated by the server-side Web address and other information, and is encrypted by the private key of a third-party institution, the middleman cannot tamper with it; Therefore, the key problem is the authenticity of the certificate signature;

The main idea of https is to add ssl security layer on the basis of http, that is, the above authentication process;

2. TCP three handshakes and four waves

Reference answer

The reason why three handshakes are three is to ensure that both client and server let each other know that their receiving and sending capabilities are OK.

For the first time, the client = > server can only judge that the client has the sending ability

The second time server = > client, the client can judge that the server has the ability to send and receive.

At this time, the client needs to let the server know that its receiving capacity is OK, so there is a third time

The third time, both client = > server ensure that their receiving and sending capabilities are free from problems

Among them, in order to ensure that the subsequent handshake is to answer the previous handshake, each handshake will carry an identification seq, and the subsequent ACK will add one to confirm this seq.

3. What are the advantages and disadvantages of img iframe script to send cross domain requests?

Reference answer


  • Advantages: after the cross domain is completed, there is no problem with DOM operation and JavaScript calls between each other

  • Disadvantages: 1. If the result is to be delivered with URL parameters, it means that it needs to be delivered separately when the amount of result data is large, which is very annoying. 2. 2. Another is brought by iframe itself. The interaction between the parent page and iframe itself has security restrictions.


  • Advantages: it can directly return data in json format, which is convenient for processing

  • Disadvantages: only GET requests are accepted

Picture ping

  • Advantages: you can access any url, which is generally used for click tracking and page analysis

  • Disadvantages: you cannot access the response text. You can only listen for the response

4. What is the difference between http and https?

Reference answer

The data transmitted by http is unencrypted, that is, in clear text. Netscape has set up SSL protocol to encrypt the data transmitted by http protocol. In short, https protocol is a network protocol constructed by http and SSL protocol for encrypted transmission and identity authentication, which has higher security than http protocol. The main differences are as follows:

  • HTTP protocol requires ca certificate, and the cost is high.
  • http is a hypertext transmission protocol, information is plaintext transmission, and https is a secure ssl encrypted transmission protocol.
  • The ports are different with different linking methods. Generally speaking, the port of http protocol is 80 and the port of https is 443
  • http connection is simple and stateless; HTTPS protocol is a network protocol constructed by SSL+HTTP protocol, which can carry out encrypted transmission and identity authentication. It is safer than http protocol.

5. What is Bom? What are the common Bom attributes?

Reference answer

Bom is a browser object

location object

  • location.href -- returns or sets the URL of the current document
  • – returns the part of the query string in the URL. For example ... return the contents after (?)? id=5&name=dreamdu
  • location.hash – returns the content after the URL # and if not #, returns null – returns the domain name part of the URL, such as
  • location.hostname – returns the main domain name part of the URL, such as
  • location.pathname – returns the part after the domain name of the URL. For example Return / XHTML/
  • location.port – returns the port portion of the URL. For example Return to 8080
  • location.protocol – returns the protocol part of the URL. For example Return the content in front of (/ /). Http:
  • location.assign – sets the URL of the current document
  • location.replace() – set the URL of the current document and remove the URL location.replace(url) from the address list of the history object;
  • location.reload() – reloads the current page

history object

  • history.go() – forward or backward the specified number of pages
  • history.go(num); history.back() – back one page
  • history.forward() – forward one page

Navigator object

  • navigator.userAgent – returns a string representation of the user agent header (that is, a string including browser version information, etc.)
  • Navigator.cookie enabled – returns whether the browser supports (enables) cookies

6. Differences among Cookie, sessionStorage and localStorage

Reference answer

Common ground: they are stored on the browser side and are homologous


cookie data is always carried in the http request of the same origin (even if it is not required), that is --
Cookies are passed back and forth between the browser and the server.

sessionStorage and localStorage do not automatically send data to the server, but only save it locally.

Cookie data also has the concept of path, which can limit the cookie to only belong to a certain path, and the storage size is very small, only about 4K. (key: it can be passed back and forth between the browser and the server. The storage capacity is small, only about 4K)


It is only valid before the current browser window is closed, so it is naturally impossible to persist. localStorage: it is always valid, and the window or browser is always saved when it is closed, so it is used as persistent data; Cookies are only valid until the set cookie expiration time, even if the window or browser is closed. (key: it is a reply process. It disappears after closing the browser. The session is a reply. When the pages are different, even if the same page is opened twice, it is regarded as the same reply.)


localStorage is shared in all source windows; Cookies are also shared in all cognate windows. (key: windows of the same origin will be shared and will not become invalid. It will always take effect whether the window or browser is closed or not)
The role of cookie s is supplemented:

Save user login status.

For example, the user id is stored in a cookie, so that users do not need to log in again when they visit the page next time. Many forums and communities now provide this function. Cookies can also be set to expire. When the time limit is exceeded, the cookie will disappear automatically. Therefore, the system can often prompt the user to stay logged in: common options include one month, three months, one year, etc.

Track user behavior.

For example, a weather forecast website can display the local weather according to the area selected by the user. If you need to select the location every time, it is cumbersome. It will be very humanized after using cookie s. The system can remember the last visited region. When you open the page next time, it will automatically display the weather of the last user's region. Because everything is done in the background, such a page is like customized for a user, which is very convenient to use

Customize the page.

If the website provides the function of skin changing or layout changing, cookie s can be used to record the user's options, such as background color, resolution, etc. When the user visits the next time, the interface style of the last visit can still be saved.

7. How cookies protect against XSS attacks

Reference answer

XSS (cross site scripting attack) means that the attacker embeds javascript scripts in the returned HTML. In order to mitigate these attacks, set cookies need to be added to the HTTP header:

  • httponly - this attribute prevents XSS, which prevents javascript scripts from accessing cookie s.
  • secure - this property tells the browser to send cookie s only when the request is https.

The result should be: set cookie =

8. What is the difference between browser and Node event loops?

Reference answer

One of the main differences is that the order of handling asynchronous events is different between the browser's event loop and nodejs' event loop. There are micro events in nodejs; Promise belongs to micro event, and the processing order of asynchronous events is different from that of the browser. The order between nodejs V11.0 and above is the same

function test () {
    setTimeout(() => {
        Promise.resolve().then(() => {console.log('children2-1')})
    }, 0)
    setTimeout(() => {
        Promise.resolve().then(() => {console.log('children3-1')})
    }, 0)
    Promise.resolve().then(() => {console.log('children1')})


// The execution results of the above code in versions below node11 (execute all macro tasks first, and then micro tasks)
// start
// end
// children1
// children2
// children3
// children2-1
// children3-1

// Execution results of the above code in node11 and browser (macro task and micro task are executed in sequence)
// start
// end
// children1
// children2
// children2-1
// children3
// children3-1

9. Brief description of HTTPS man in the middle attack

Reference answer

https protocol is composed of http + ssl protocol. For the specific link process, please refer to the overview of SSL or TLS handshake

The process of man in the middle attack is as follows:

  1. The server sends the public key to the client.
  2. The attacker intercepts the public key and keeps it in his hand.
  3. Then the attacker generates a [forged] public key and sends it to the client.
  4. After receiving the forged public key, the client generates an encrypted hash value and sends it to the server.
  5. The attacker obtains the encrypted hash value and decrypts it with his own private key to obtain the true secret key.
  6. At the same time, a false encrypted hash value is generated and sent to the server.
  7. The server decrypts the private key to obtain a false secret key.
  8. The server encrypts the transmission information with a secret key


The server adds the CA certificate to the public key of the sending browser, and the browser can verify the validity of the CA certificate

10. Some web front-end optimization strategies

Reference answer

(1) . reduce the number of HTTP requests

This strategy is basically known to all front-end people, and it is also the most important and effective. It is said to reduce HTTP requests. What happens when there are more requests?

First, each request has a cost, including both time cost and resource cost.

A complete request needs a "long" and complex process of DNS addressing, establishing a connection with the server, sending data, waiting for the server response and receiving data.

The time cost is that users need to see or "feel" this resource and have to wait for the end of this process. In terms of resources, each request needs to take up bandwidth because it needs to carry data.

In addition, since there is an upper limit on the number of concurrent requests made by the browser, when the number of requests is large, the browser needs to make requests in batches, which will increase the waiting time of users and give users the impression that the site speed is slow. Even if the resources on the first screen that users can see have been requested, the progress bar of the browser will always exist.

(2) Simplify the page from the design and implementation level

If your page is as simple as Baidu home page, then the next rules are basically unnecessary. It is the most direct way to keep the page concise and reduce the use of resources.

If this is not the case and your page needs gorgeous skin, continue to read the following content.

(3) . reasonably set HTTP cache

The power of caching is powerful. Proper cache settings can greatly reduce HTTP requests.

Take YOUAH homepage as an example. When the browser is not cached, a total of 78 requests will be sent for access, with a total of more than 600 k data. When the second access, that is, after the browser has been cached, there are only 10 requests for access, with a total of more than 20 K data
(it should be noted here that if you refresh the page directly with F5, the effect is different. In this case, the number of requests is the same, but the request server of cached resources responds with 304. Only the Header has no Body, which can save bandwidth.)

What is the reasonable setting? The principle is very simple. The more you can cache, the better. The longer you can cache, the better.

For example, for rarely changed picture resources, you can directly set a long expiration header through Expires in the HTTP Header;

For resources that change infrequently and may change, last modified can be used for request verification. Make resources stay in the cache longer as possible.

(4) . resource consolidation and compression

If possible, merge external scripts and styles as much as possible, and combine multiple into one.

In addition, CSS, Javascript and Image can be compressed with corresponding tools, which often saves a lot of space after compression.

(5). CSS Sprites

Merging CSS images is another good way to reduce the number of requests.

(6). Inline Images

Using data: URL scheme to embed images into pages or CSS is a good way if resource management problems are not considered.

If the page is embedded, it will increase the volume of the page and cannot use the browser cache. Images used in CSS are more ideal.

(7). Lazy Load Images

This strategy does not necessarily reduce the number of HTTP requests, but it can reduce the number of HTTP requests under certain conditions or when the page is just loaded.

For pictures, only the first screen can be loaded when the page is just loaded, and subsequent pictures can be loaded only when the user continues to scroll back.

In this way, if the user is only interested in the content of the first screen, the remaining picture requests are saved.

Yes, the home page used to cache the picture address after the first screen in the Textarea tag when loading, and only "inert" loading when the user scrolls down the screen.

11. Do you understand the performance problems caused by redrawing and reflow of your browser

Reference answer

Repaint and Reflow

Redraw and reflow are part of the rendering steps, but they have a significant impact on performance.

Redrawing is when a node needs to change its appearance without affecting the layout. For example, changing color is called redrawing
Reflow is when the layout or geometric properties need to be changed, it is called reflow.
Reflow is bound to redraw, and redraw does not necessarily lead to reflow. The cost of backflow is much higher. Changing deep-seated nodes is likely to lead to a series of backflow of parent nodes.

Therefore, the following actions may cause performance problems:

  • Change window size
  • Change font
  • Add or remove styles
  • Text change
  • Positioning or floating
  • Box model

What many people don't know is that redrawing and reflow are actually related to Event loop.

  1. After Event loop executes Microtasks, it will judge whether the document needs to be updated.
    Because the browser has a refresh rate of 60Hz, it will be updated every 16ms.

  2. Then judge whether there is a resize or scroll. If there are, the event will be triggered. Therefore, the resize and scroll events will be triggered at least 16ms, and the throttling function is provided.

  3. Judge whether media query is triggered

  4. Update animation and send events

  5. Determine whether there are full screen operation events

  6. Execute requestAnimationFrame callback

  7. Execute the IntersectionObserver callback. This method is used to determine whether the element is visible. It can be used for lazy loading, but the compatibility is not good

  8. Update interface

  9. That's what you might do in a frame. If there is idle time in a frame, the requestIdleCallback callback will be executed.

Reduce redrawing and reflow

Use translate instead of top

<div class="test"></div>
  .test {
      position: absolute;
      top: 10px;
      width: 100px;
      height: 100px;
      background: red;
  setTimeout(() => {
      // Cause backflow
      document.querySelector('.test') = '100px'
  }, 1000)
  • Replace display: none with visibility, because the former will only cause redrawing and the latter will cause reflow (changing the layout)
    Modify the DOM offline. For example, first give the DOM to display: none (reflow once), then modify it 100 times, and then display it
    Don't put the attribute values of DOM nodes in a loop as variables in the loop
for(let i = 0; i < 1000; i++) {
  // Getting offsetTop will cause backflow because you need to get the correct value
  • Do not use the table layout. A small change may cause the whole table to be rearranged

  • The faster the animation speed, the more reflow times. You can also choose to use requestAnimationFrame

  • CSS selectors match and search from right to left to avoid too deep DOM depth

  • Turn the frequently running animation into a layer, which can prevent the reflow of this node from affecting other elements. For example, for the video tag, the browser will automatically change the node into a layer.

3, react, Vue

1. Why should I write a key in the list component when writing a React / Vue project? What is its function?

Reference answer

vue and react both use diff algorithm to compare the old and new virtual nodes, so as to update the nodes.

In the diff function of vue (it is recommended to understand the diff algorithm process first).

In cross comparison, when there is no result of cross comparison between the new node and the old node, the key in the old node array will be compared according to the key of the new node, so as to find the corresponding old node (here corresponds to a map mapping of key = > index). If it is not found, it is considered as a new node. If there is no key, the corresponding old node will be found by traversal. One is a map map, the other is a traversal search. In contrast. Map mapping is faster.
The source code of vue is as follows:

// vue project Src / core / vdom / patch.js - line 488
// The following is the formatted code for readability

// oldCh is an old array of virtual nodes
if (isUndef(oldKeyToIdx)) {
  oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
if(isDef(newStartVnode.key)) {
  // Get by map
  idxInOld = oldKeyToIdx[newStartVnode.key]
} else {
  // Traversal acquisition
  idxInOld = findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)

Create map function

function createKeyToOldIdx (children, beginIdx, endIdx) {
  let i, key
  const map = {}
  for (i = beginIdx; i <= endIdx; ++i) {
    key = children[i].key
    if (isDef(key)) map[key] = i
  return map

Traversal search

// sameVnode is a function that compares whether old and new nodes are the same
 function findIdxInOld (node, oldCh, start, end) {
    for (let i = start; i < end; i++) {
      const c = oldCh[i]
      if (isDef(c) && sameVnode(node, c)) return i

2. When is setState synchronous and asynchronous in React?

Reference answer

In React, if it is an event processing triggered by React (such as an event processing triggered by onClick), calling setState will not update this.state synchronously, and other setState calls will execute this.state synchronously.

The so-called "in addition" refers to the event handling functions directly added through addEventListener to bypass React, as well as the asynchronous calls generated through setTimeout/setInterval.

**Reason: * * in the implementation of the setState function of React, whether to update this.state directly or put it in the queue will be determined according to a variable isBatchingUpdates. I'll talk about it later. isBatchingUpdates is false by default, which means that setState will update this.state synchronously. However, there is a function batchedUpdates, which will modify isBatchingUpdates to true, When React calls the batchedUpdates before calling the event handling function, the consequence is that the event handling process setState controlled by React will not update this.state synchronously.

3. What is output below

class Example extends React.Component {
  constructor() {
    this.state = {
      val: 0
  componentDidMount() {
    this.setState({val: this.state.val + 1});
    console.log(this.state.val);    // 1st log

    this.setState({val: this.state.val + 1});
    console.log(this.state.val);    // Second log

    setTimeout(() => {
      this.setState({val: this.state.val + 1});
      console.log(this.state.val);  // 3rd log

      this.setState({val: this.state.val + 1});
      console.log(this.state.val);  // 4th log
    }, 0);

  render() {
    return null;
1,The first and second were in react In its own life cycle, when triggered isBatchingUpdates by true,Therefore, updates are not performed directly state,But joined dirtyComponents,Therefore, the status 0 before update is obtained during printing.

2,twice setState When, get this.state.val Both are 0, so 0 is set to 1 during execution react The internal will be merged and executed only once. After setting state.val The value is 1.

3,setTimeout Code in, when triggered isBatchingUpdates by false,Therefore, it can be updated directly, so it is connected with output 2 and 3.

Output: 0 0 2 3

4. Why does virtual dom improve performance?

Reference answer

Virtual DOM is equivalent to adding a cache between js and real dom. dom diff algorithm is used to avoid unnecessary DOM operations, so as to improve performance.

The specific implementation steps are as follows:

  • The structure of DOM tree is represented by JavaScript object structure; Then use this tree to build a real DOM tree and insert it into the document

  • When the state changes, reconstruct a new object tree. Then compare the new tree with the old tree and record the difference between the two trees

  • Apply the differences recorded in step 2 to the real DOM tree built in step 1, and the view is updated.

4, css

1. Analyze and compare the advantages and disadvantages of opacity: 0, visibility: hidden, display: none and applicable scenarios

Reference answer


  • display:none: it will make the elements completely disappear from the rendering tree. When rendering, it does not occupy any space and cannot be clicked,
  • visibility: hidden: elements will not disappear from the rendering tree. Rendering elements continue to occupy space, but the content is invisible and cannot be clicked
  • opacity: 0: elements will not disappear from the rendering tree. Rendering elements continue to occupy space, but the content is invisible. You can click


  • display: none and opacity: 0: it is a non inherited attribute. The descendant node disappears. Because the element disappears from the rendering tree, it cannot be displayed by modifying the descendant node attribute.
  • visibility: hidden: it is an inherited attribute. The descendant node disappears. Because it inherits hidden, set visibility: visible; You can make descendant nodes explicit.


  • displaynone: modifying the element will cause document reflow. The screen reader will not read the content of the display: none element, which consumes a lot of performance
  • visibility:hidden: modifying an element will only cause redrawing of the element, with less performance consumption. The screen reader reads the content of the visibility:hidden element
  • opacity: 0: modifying elements will cause redrawing and consume less performance

Connection: they all make elements invisible

2. What are the ways to clear floats? Which one is better?

Reference answer

There are three commonly used. clearfix, clear:both,overflow:hidden;

The better is. clearfix, the pseudo element panacea version. The latter two have limitations

.clearfix:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;

Why not zoom ,_height these,IE6,7 Such needs csshack We don't think about it anymore
.clearfix There is another way to write,

.clearfix:before, .clearfix:after {

use display:table To avoid outer margins margin Caused by overlap margin Collapse,
Internal elements become by default table-cell Form of cell
  • clear:both: if it is used on adjacent elements in the same container, it is good. Sometimes there are some problems outside the container, such as the collapse of wrapping elements in adjacent containers

  • overflow:hidden: if used in the same container, BFC can be formed to avoid element collapse caused by floating

4. What is css sprite and what are its advantages and disadvantages

Reference answer

Concept: splice multiple small pictures into one picture. Adjust the background pattern to be displayed through background position and element size.


Reduce the number of HTTP requests and greatly improve the page loading speed
Increase the picture information repeatability, improve the compression ratio and reduce the picture size
It is convenient to change the style. You only need to modify the color or style on one or several pictures

Picture merging trouble
Maintenance is troublesome. Modifying a picture may need to rearrange the whole picture and style

5. The difference between link and @ import

Reference answer

link is HTML and @ import is CSS
link supports parallel downloading to the maximum extent. Too much nesting of @ import leads to serial downloading and FOUC
link you can specify candidate styles through rel="alternate stylesheet"
The browser supports link earlier than @ import. You can use @ import to hide the style from the old browser
@import must precede the style rule, and other files can be referenced in the css file
Overall: link is better than @ import

6,display: block; And display: inline; Differences between

Reference answer

block element features:

  1. When in a regular flow, if the width is not set, the parent container is automatically filled
  2. margin/padding can be applied
  3. If the height is not set, the height is extended to include child elements in the regular flow
  4. Between front and rear element positions (exclusive horizontal space) in layout when in regular flow
  5. Ignore vertical align

inline element features

  1. The layout is arranged according to the direction in the horizontal direction

  2. No wrapping occurs before or after the element

  3. Controlled by white space

  4. margin/padding is invalid in the vertical direction and valid in the horizontal direction

  5. The width/height attribute is not valid for elements in non replacement lines. The width is determined by the content of the element

  6. The row box height of the elements in the non replacement row is determined by line height, and the row box height of the elements in the replacement row is determined by height, margin, padding and border

  7. When floating or absolute positioning, it is converted to block

  8. The vertical align attribute takes effect

7. How to clean up floating when a container contains several floating elements

Reference answer

  • Add additional elements and set clear: both before the container element closes the label
  • The parent element triggers the block level formatting context (see the block level visualization context section)
  • Set container element pseudo element for cleanup
* Use in standard browser
* 1 content The content is blank, which is used to fix the problem in the document under opera
*   contenteditable Property to clean up the white space above and below the floating element
* 2 Use display, use table instead of block: you can prevent containers and
*   The sub element top margin is folded, which can make the cleaning effect consistent with BFC and IE6/7
*   zoom: 1;agreement

.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */

.clearfix:after {
    clear: both;

* IE 6/7 Use under
* Include floats by triggering hasLayout
.clearfix {
    *zoom: 1;

8. Differences between PNG, GIF and JPG and how to select them

Reference answer


8-bit pixels, 256 colors
lossless compression
Support simple animation
Support boolean transparency
Suitable for simple animation


Color limited to 256
Lossy compression
Controllable compression quality
Transparency is not supported
Suitable for photos


There are PNG8 and truecolor PNG
PNG8 is similar to GIF. The upper color limit is 256. The file is small. It supports alpha transparency and has no animation
Suitable for icons, backgrounds, buttons

9. Relationship between display, float and position

Reference answer

If display is none, neither position nor float will work. In this case, the element will not generate a box
Otherwise, if the position value is absolute or fixed, the box is absolutely positioned, the calculated value of float is none, and display is adjusted according to the following table.
Otherwise, if the float is not none, the box is floating, and the display is adjusted according to the following table
Otherwise, if the element is the root element, display adjusts according to the following table
In other cases, the value of display is the specified value. To sum up, the display needs to be adjusted for absolute positioning, floating and root elements

10. How to center an element horizontally

Reference answer

If the element to be centered is the inline element in the regular flow, set text align: Center for the parent element; Can be achieved

If the element to be centered is the block element in the regular flow

1) Set the width for the element,
2) Set the left and right margin to auto.
3) Under IE6, text align: center should be set on the parent element;

Then restore the required values to the child elements

  <div class="content">
  aaaaaa aaaaaa a a a a a a a a

  body {
      background: #DDD;
      text-align: center; /* 3 */
  .content {
      width: 500px;      /* 1 */
      text-align: left;  /* 3 */
      margin: 0 auto;    /* 2 */

      background: purple;

If the element to be centered is a floating element

1) Set the width for the element,
2)position: relative;
3) The floating direction offset (left or right) is set to 50%,
4) The margin in the floating direction is set to half the width of the element multiplied by - 1

  <div class="content">
  aaaaaa aaaaaa a a a a a a a a

  body {
      background: #DDD;
  .content {
      width: 500px;         /* 1 */
      float: left;

      position: relative;   /* 2 */
      left: 50%;            /* 3 */
      margin-left: -250px;  /* 4 */

      background-color: purple;

If the element to be centered is an absolute positioning element

1) Sets the width for the element
2) The offset is set to 50%
3) The offset direction outer margin is set to half the element width multiplied by - 1

  <div class="content">
  aaaaaa aaaaaa a a a a a a a a

  body {
      background: #DDD;
      position: relative;
  .content {
      width: 800px;

      position: absolute;
      left: 50%;
      margin-left: -400px;

      background-color: purple;

If the element to be centered is an absolute positioning element

1) Sets the width for the element
2) Set the left and right offsets to 0
3) Set the left and right outer margins to auto

  <div class="content">
  aaaaaa aaaaaa a a a a a a a a

  body {
      background: #DDD;
      position: relative;
  .content {
      width: 800px;

      position: absolute;
      margin: 0 auto;
      left: 0;
      right: 0;

      background-color: purple;

5, JavaScript

1. JS has several data types, among which are the basic data types?

Reference answer

Seven data types

  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol (ECMAScript 6 new definition)
  • Object
    (before ES6) five of them are basic types: string,number,boolean,null,undefined,

The Symbol from ES6 is also the original data type and represents a unique value

Object is a reference type (with a large range), including arrays and functions,

2. Whether the Promise constructor is executed synchronously or asynchronously, what about the then method?

Reference answer

const promise = new Promise((resolve, reject) => {

promise.then(() => {


The output is:

promise Constructors are executed synchronously, then Methods are executed asynchronously
Promise new The code inside will be executed immediately then Yes, micro tasks will be executed when this task is completed setTimeout Yes, the macro task will be executed the next time the task is executed

3. Four design patterns of JS

Reference answer

Factory mode

A simple factory model can be understood as solving multiple similar problems;

function CreatePerson(name,age,sex) {
    var obj = new Object(); = name;
    obj.age = age; = sex;
    obj.sayName = function(){
    return obj;
var p1 = new CreatePerson("longen",'28','male');
var p2 = new CreatePerson("tugenhua",'27','female');
console.log(; // longen
console.log(p1.age);  // 28
console.log(;  // male
console.log(p1.sayName()); // longen

console.log(;  // tugenhua
console.log(p2.age);   // 27
console.log(;   // female
console.log(p2.sayName()); // tugenhua  

Singleton mode

It can only be instantiated once (the constructor adds properties and methods to the instance)

// Monomer mode
var Singleton = function(name){ = name;
Singleton.prototype.getName = function(){
// Get instance object
var getInstance = (function() {
    var instance = null;
    return function(name) {
        if(!instance) {//It is equivalent to a disposable valve and can only be instantiated once
            instance = new Singleton(name);
        return instance;
// Test the instance of monomer mode, so a =
var a = getInstance("aa");
var b = getInstance("bb");  

Sandbox mode

Put some functions into self executing functions, but expose the interface with closures, receive the exposed interface with variables, and then call the values inside, otherwise the values inside cannot be used

let sandboxModel=(function(){
    function sayName(){};
    function sayAge(){};

Publisher subscription mode

For example, if we are concerned about a official account, then he will send you a new message.

//Publisher and subscription mode
    var shoeObj = {}; // Define publisher
    shoeObj.list = []; // The cache list stores the subscriber callback function

    // Add subscriber
    shoeObj.listen = function(fn) {
        shoeObj.list.push(fn); // Add subscription message to cache list

    // Release news
    shoeObj.trigger = function() {
            for (var i = 0, fn; fn = this.list[i++];) {
                fn.apply(this, arguments);//The first parameter just changes this of fn,
     // Xiao Hong subscribes to the following message
    shoeObj.listen(function(color, size) {
        console.log("The color is:" + color);
        console.log("Size:" + size);

    // Xiaohua subscribes to the following message
    shoeObj.listen(function(color, size) {
        console.log("The color to print again is:" + color);
        console.log("Print the size again:" + size);
    shoeObj.trigger("gules", 40);
    shoeObj.trigger("black", 42);  

The code implementation logic uses an array to store subscribers. The notification method in the publisher callback function is to traverse the subscriber array and pass the publisher content into the subscriber array

4. List the methods of creating instances in a centralized way

Reference answer

1. Literal quantity

let obj={'name':'Zhang San'}

2.Object constructor creation

let Obj=new Object()'Zhang San'

3. Create objects using factory mode

function createPerson(name){
 var o = new Object(); = name;
 return o; 
var person1 = createPerson('Zhang San');

4. Create objects using constructors

function Person(name){ = name;
var person1 = new Person('Zhang San');

5. Briefly describe the front-end event flow

Reference answer

Interaction with javascript in HTML is realized through event driven, such as mouse click event onclick, page scrolling event onscroll, etc. event listeners can be added to documents or elements in documents to subscribe to events.

To know when these events are called, you need to understand the concept of "event flow".

What is event flow: event flow describes the order in which events are received from the page. DOM2 level event flow includes the following stages.

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

addEventListener: addEventListener is the operation of the specified event handler added by DOM2 level events

This method takes three parameters: the name of the event to be processed, the function as the event handler, and a Boolean value.

Finally, if the Boolean parameter is true, it means that the event handler is called in the capture phase; If false, the event handler is called during the bubbling phase.

IE only supports event bubbling.

6. What is Function.proto(getPrototypeOf)?

Reference answer

Get the prototype of an object, which can be used in chrome__ proto__ Or in ES6, you can use the form of Object.getPrototypeOf.

So what is Function.proto? That is to say, the object from which the Function is inherited, let's make the following judgment.

Function.__proto__==Object.prototype //false

We found that the prototype of Function is also Function.

We can clarify this relationship with a diagram:

7. Briefly describe the prototype / constructor / instance

Reference answer

  • Prototype: a simple object used to implement the property inheritance of the object. It can be simply understood as the father of the object. In Firefox and Chrome, each JavaScript object contains a__ proto__ The (non-standard) attribute points to its parent (the prototype of the object), which can be obj__ proto__ Visit.
  • Constructor: you can create a new function of an object through new.
  • Instance: the object created by constructor and new is an instance. Instance pass__ proto__ Point to the prototype, and point to the constructor through the constructor.

Here's a chestnut. Take Object as an example. Our commonly used Object is a constructor, so we can build instances through it.

// example
const instance = new Object()

At this time, the instance is instance and the constructor is Object. We know that the constructor has a prototype attribute pointing to the prototype, so the prototype is:

// prototype
const prototype = Object.prototype

Here we can see the relationship between the three:

example.__proto__ === prototype

prototype.constructor === Constructor

Constructor.prototype === prototype

// This line is actually obtained based on the prototype, which can be understood as a reflection ray based on the prototype
// For example: 
// const o = new Object()
// o.constructor === Object   --> true
// o.__proto__ = null;
// o.constructor === Object   --> false
 example.constructor === Constructor

8. Briefly describe JS inheritance and give examples

Reference answer

In JS, inheritance usually refers to prototype chain inheritance, that is, specify the prototype and inherit the properties or methods on the prototype through the prototype chain.

Optimization: Holy Grail mode

var inherit = (function(c,p){
  var F = function(){};
  return function(c,p){
      F.prototype = p.prototype;
      c.prototype = new F();
      c.uber = p.prototype;
      c.prototype.constructor = c;

Use the syntax of ES6: sugar class / extends

9. Function coritization

Reference answer

In functional programming, functions are first-class citizens. So what is the function coriolism?

Function corrilization refers to the technology of converting a function that can receive multiple parameters into a function that receives a single parameter and returns a new function that receives the remaining parameters and returns the result.

The main functions and characteristics of function coritization are parameter reuse, early return and delayed execution.

In a function, the technique of first filling in several parameters and then returning a new function is called function coritization. Generally, it can be used to preset general parameters for functions for repeated calls without invading functions.

const add = function add(x) {
    return function (y) {
        return x + y

const add1 = add(1)

add1(2) === 3
add1(20) === 21

10. Tell me the difference between bind, call and apply?

Reference answer

Both call and apply are to change the direction of this. The functions are the same, but the methods of parameter transmission are different.

In addition to the first parameter, call can receive a parameter list, and apply accepts only one parameter array.

let a = {
    value: 1
function getValue(name, age) {
}, 'yck', '24')
getValue.apply(a, ['yck', '24'])

Bind has the same function as the other two methods, except that this method will return a function. And we can achieve curry through bind.

(the following is an extended introduction to these three methods)

How to implement a bind function

For the implementation of the following functions, we can think from several aspects

If the first parameter is not passed in, it defaults to window
Changed the point of this so that the new object can execute the function. So can the idea be to add a function to a new object and delete it after execution?

Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  var _this = this
  var args = [...arguments].slice(1)
  // Returns a function
  return function F() {
    // Because a function is returned, we can use new F(), so we need to judge
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    return _this.apply(context, args.concat(...arguments))

How to implement a call function

Function.prototype.myCall = function (context) {
  var context = context || window
  // Add a property to the context
  //, 'yck', '24') => a.fn = getValue
  context.fn = this
  // Take out the parameters behind the context
  var args = [...arguments].slice(1)
  //, 'yck', '24') => a.fn('yck', '24')
  var result = context.fn(...args)
  // Delete fn
  delete context.fn
  return result

How to implement an apply function

Function.prototype.myApply = function (context) {
  var context = context || window
  context.fn = this

  var result
  // You need to determine whether to store the second parameter
  // If so, expand the second parameter
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()

  delete context.fn
  return result

11. Characteristics of arrow function

Reference answer

function a() {
    return () => {
        return () => {

In fact, the arrow function does not have this. This in this function only depends on this of the first function outside it that is not an arrow function.

In this example, because the call to a matches the first case in the previous code, this is window. And once this is bound to the context, it will not be changed by any code.

6, Program reading questions

1. What is the output of the following program?

function sayHi() {
  var name = "Lydia";
  let age = 21;

  • A: Lydia and undefined
  • B: Lydia and ReferenceError
  • C: ReferenceError and 21
  • D: undefined and ReferenceError

Reference answer

In the function, we first declare the name variable with the var keyword. This means that the variable will be promoted during the creation phase (JavaScript will allocate memory space for the variable during the creation phase), and the default value is undefined until we actually execute the row using the variable. We haven't assigned a value to the name variable yet, so it still maintains the undefined value.

Variables declared using the let keyword (and const) will also have variable promotion, but unlike var, initialization is not promoted. They are not accessible until we declare (initialize) them. This is called a "temporary dead zone". When we try to access a variable before declaring it, JavaScript throws a ReferenceError.

How can we use the following example to verify whether there is variable promotion in let

let name = 'ConardLi'
  console.log(name) // Uncaught ReferenceError: name is not defined
  let name = 'code Secret Garden'

If there is no variable promotion for let variable, console.log(name) will output ConardLi, but the result throws ReferenceError. This well shows that let also has variable promotion, but it has a "temporary dead zone", and access is not allowed before variable initialization or assignment.

The assignment of variables can be divided into three stages:

  • Create variables to open up space in memory
  • Initialize the variable to undefined
  • Real assignment

About let, var and function:

  • let's "create" process was promoted, but initialization was not promoted.
  • var's "creation" and "initialization" have been promoted.
  • The "creation", "initialization" and "assignment" of function have been promoted.

2. What does the following code output

var a = 10;
(function () {
    a = 5
    var a = 20;

Output in sequence: undefined - > 10 - > 20

In the immediate execution function, var a = 20; The statement defines a local variable A. due to the variable declaration promotion mechanism of js, the declaration of local variable a will be promoted to the top of the function body of the immediate execution function. Since such promotion does not include assignment, the first print statement will print undefined and the last statement will print 20.

a = 5 due to variable declaration promotion; When this statement is executed, the local variable a has been declared, so its effect is to assign a value to the local variable A. at this time, window.a is still 10 of the initial assignment,

3. What are the following output results?

class Chameleon {
  static colorChange(newColor) {
    this.newColor = newColor;

  constructor({ newColor = "green" } = {}) {
    this.newColor = newColor;

const freddie = new Chameleon({ newColor: "purple" });
  • A: orange
  • B: purple
  • C: green
  • D: TypeError

Answer: D

The colorChange method is static.

Static methods exist only in the constructor that created them and cannot be passed to any children. Since freddie is a child object and the function will not be passed, there is no freddie method on the freddie instance: throw TypeError.

4. When will 1 be output in the following code?

var a = ?;
if(a == 1 && a == 2 && a == 3){

Reference answer
Because = = will perform implicit type conversion, we can override the toString method

var a = {
  i: 1,
  toString() {
    return a.i++;

if( a == 1 && a == 2 && a == 3 ) {

5. What are the following output results?

var obj = {
    '2': 3,
    '3': 4,
    'length': 2,
    'splice': Array.prototype.splice,
    'push': Array.prototype.push

Reference answer

1. Set obj [2] = 1 using the first push method of obj object; obj.length+=1
2. Use the second push, and set obj [3] = 2 in the push method of obj object; obj.length+=1
3. When using console.log output, because obj has length attribute and splice method, it is printed as an array
4. When printing, because the value at subscript 0 and 1 is not set for the array, it is printed as empty, and the active obj[0] is obtained as undefined

6. What is the output of the following code?

var a = {n: 1};
var b = a;
a.x = a = {n: 2};


Reference answer


First, a and B reference the {n:2} object at the same time, and then execute the a.x = a ={n:2} statement. Although the assignment is correct from right to left, the priority of. Is higher than =. Therefore, executing a.x first here is equivalent to adding an attribute x to the {n:1} object pointed to by a (or b), that is, the object will become {n:1;x:undefined}. Then, the assignment is performed from right to left according to the normal situation. At this time, when a ={n:2} is executed, the reference of a changes and points to the new object {n:2}, while B still points to the old object. Later, when a.x = {n:2} is executed, a will not be parsed again, but the a when a.x was originally parsed, that is, the old object. Therefore, the value of X of the old object is {n:2}, and the old object is {n:1;x:{n:2}, which is referenced by B.
When outputting a.x later, you have to parse A. at this time, a refers to a of the new object, and the new object has no X attribute, so undefined is output during access; When accessing b.x, the value of X of the old object will be output, that is, {n:2}.

7. What is the output of the following code?

function checkAge(data) {
  if (data === { age: 18 }) {
    console.log("You are an adult!");
  } else if (data == { age: 18 }) {
    console.log("You are still an adult.");
  } else {
    console.log(`Hmm.. You don't have an age I guess`);

checkAge({ age: 18 });

Reference answer

Hmm... You don't have an age I guess

In comparing equality, primitive types are compared by their values, while objects are compared by their references. JavaScript checks whether an object has a reference to the same location in memory.

The objects we pass as parameters and the objects we use to check for equality are located in different locations in memory, so their references are different.

This is why {age: 18} = = {age: 18} and {age: 18} = = {age: 18} return false.

8. What is the output of the following code?

const obj = { 1: "a", 2: "b", 3: "c" };
const set = new Set([1, 2, 3, 4, 5]);


Reference answer

true true false true

All object keys (excluding Symbols) will be stored as strings, even if you don't have a key of a given string type. This is why obj.hasOwnProperty ('1 ') also returns true.

The above statement does not apply to Set. There is no "1" in our Set: set.has ('1 ') returns false. It has numeric type 1, and Set. Has (1) returns true.

9. What is the output of the following code?

// example 1
var a={}, b='123', c=123;  

// example 2
var a={}, b=Symbol('123'), c=Symbol('123');  

// example 3
var a={}, b={key:'123'}, c={key:'456'};  

Reference answer

This problem examines the conversion of key names of objects.

  • Object key names can only be string and Symbol types.
  • Other types of key names are converted to string types.
  • Object to string will call the toString method by default.
// example 1
var a={}, b='123', c=123;
// The key name of c will be converted to the string '123', where b will be overwritten.
// Output c

// example 2
var a={}, b=Symbol('123'), c=Symbol('123');  
// b is a Symbol type and does not require conversion.
// c is a Symbol type and does not require conversion. The values of any Symbol type are not equal, so b will not be overwritten.
// Output b

// example 3
var a={}, b={key:'123'}, c={key:'456'};  
// b is neither a string nor a Symbol type. It needs to be converted to a string.
// The object type will call the toString method to convert it into a string [object Object].
// c is neither a string nor a Symbol type. It needs to be converted to a string.
// The object type will call the toString method to convert it into a string [object Object]. b will be covered here.
// Output c

10. What is the output of the following code?

(() => {
  let x, y;
  try {
    throw new Error();
  } catch (x) {
    (x = 1), (y = 2);

Reference answer

1 undefined 2

The catch block receives parameter x. When we pass parameters, this is different from the x of the variable.

This variable x belongs to the scope of catch.

After that, we set the variable of this block level scope to 1 and set the value of variable y. Now, let's print the variable x of the block level scope, which is equal to 1.

Outside the catch block, X is still undefined and y is 2. When we want console.log(x) outside the catch block, it returns undefined and y returns 2.

11. What is the output of the following code?

function Foo() {
    Foo.a = function() {
    this.a = function() {
Foo.prototype.a = function() {
Foo.a = function() {
let obj = new Foo();

Reference answer

The output order is 4 2 1

function Foo() {
    Foo.a = function() {
    this.a = function() {
// The above is only the construction method of Foo. No instance is generated and it is not implemented at the moment

Foo.prototype.a = function() {
// Now the prototype method a is mounted on Foo, and the method output value is 3

Foo.a = function() {
// Now the direct method a is mounted on Foo, and the output value is 4

// The a method on Foo is executed immediately, which is just defined, so
// #Output 4

Added by shane18 on Sun, 24 Oct 2021 13:01:23 +0300