Basic JavaScript interview questions (with answers)

In recent years, more and more programmers engaged in web front-end development need to use JavaScript. This article mainly compiles some of the most common JavaScript interview questions and answers.

Introducing JavaScript data types

Value type (basic type): String, Number, Boolean, Null, Undefined, Symbol (unique value).

Reference data types: Object, Array, Function.

Note: Symbol is a new primitive data type introduced in ES6 to represent unique values.

What is the difference in storage between basic data types and reference types?

1. Different storage locations:

Basic data type: stored in the form of a stack, saving and assigning point to the data itself, using typeof to determine the type, and the storage space is fixed.

Reference type: stored in the form of a heap, saved in a pointer to the object assigned, and instanceof is used to determine the type. The storage space is not fixed.

2. Different ways of passing values:

Basic data types are passed by value, and the value of a basic data type cannot be changed.

Reference types are passed by reference, and application type values ​​can change

How to determine js type

1. typeof

You can judge 'string', 'number', 'boolean', 'undefined', 'symbol'
but when judging typeof(null) the value is 'object'; when judging array and object the value is both 'object'

2. instanceof

The principle is whether the prototype attribute of the constructor appears anywhere in the prototype chain of the object

function A() {}let a = new A();a instanceof A     //true,因为 Object.getPrototypeOf(a) === A.prototype;

3. Object.prototype.toString.call()

It is often used to judge built-in browser objects. It can judge all basic data types, even null and undefined.

Object.prototype.toString.call(null)//"[object Null]"Object.prototype.toString.call(undefined)//"[object Undefined]"Object.prototype.toString.call(Object)//"[object Function]"

4. Array.isArray()

Used to determine whether it is an array.

The difference between typeof operator, instanceof operator and isPrototypeOf() method

typeof is an operator used to detect the type of data, such as basic data types null, undefined, string, number, boolean, and reference data types object, function, but for reference data types such as regular expressions, dates, and arrays, it will all be recognized as objects

Instanceof is also an operator, which can easily identify the specific reference type of the data. The difference between it and isPrototypeOf is that it is used to detect whether the prototype of the constructor exists in the prototype chain of the specified object;

The isPrototypeOf is used to detect whether the object calling this method exists in the prototype chain of the specified object, so essentially the detection targets are different.

What is NaN

NaN stands for Not a Number. The NaN attribute is used to refer to a special non-numeric value. The attribute specified is not an illegal number.

The NaN property is the same as the Number.Nan property.

Tip: Use isNaN() to determine whether a value is a number. The reason is that NaN is not equal to any value, including itself.

Local objects in js? Built-in objects? Host object?

Native objects: ECMA-262 defines native objects as "objects provided by an ECMAScript implementation that is independent of the host environment."

包含了:Object、Function、Array、String、Boolean、Number、Date、RegExp、Error、EvalError、RangeError、ReferenceError、SyntaxError、TypeError、URIError。

Built-in objects: ECMA-262 defines built-in objects as "all objects provided by the ECMAScript implementation, independent of the host environment, that appear when the ECMAScript program starts executing." This means that the developer does not have to explicitly instantiate the built-in object, it is already instantiated. Contains: Gobal and Math.

Host object: The object provided by the host environment implemented by ECMAScript can be understood as: the object provided by the browser. All BOM and DOM are host objects.

What is the difference between stack and heap?

Stack: automatically allocated and released by the compiler to store function parameter values, local variables, etc.;

Heap: Generally allocated and released by the programmer. If the programmer does not release it, it may be released by the operating system when the program ends.

Describe the difference between the following variables: null, undefined or undeclared

null means "no object", that is, there should be no value there, and it is 0 when converted to a numerical value. Typical usage is:

(1) As a parameter of a function, it means that the parameter of the function is not an object.

(2) As the end point of the object prototype chain.

undefined means "missing value", that is, there should be a value here, but it has not been defined, and it is NaN when converted to a numerical value. Typical usage is:

(1) When a variable is declared but not assigned a value, it is equal to undefined.

(2) When calling the function, the parameter that should be provided is not provided, and the parameter is equal to undefined.

(3) The object has no assigned attributes, and the value of this attribute is undefined.

(4) When the function does not return a value, it returns undefined by default.

undeclared: js syntax error, direct use without declaration, js cannot find the corresponding context.

The difference between for..in and object.keys

Object.keys does not traverse inherited prototype properties

for...in will iterate over inherited prototype properties

What are anonymous functions in JS?

Anonymous function: It is a function without a function name, such as:

(function(x, y){
   
       alert(x + y);  })(2, 3);

An anonymous function is created here (inside the first bracket), and the second bracket is used to call the anonymous function and pass in the parameters.

Explaining function hoisting in JS

JS's default behavior of allowing declarations to be moved to the top is called hoisting. The two ways to create functions in JS are function declarations and function expressions.

function declaration

A function with specific parameters is called a function declaration and creating a variable in JS is called a declaration. like:

hoisted(); // logs "foo"function hoisted() {
   
     console.log('foo');}

function expression

When an expression is used to create a function, it is called a function expression. Such as:​​​​​​​

notHoisted(); // TypeError: notHoisted is not a functionvar notHoisted = function() {
   
      console.log('bar');};

Introduction to Js implicit conversion

In js, when an operator is operating, if the data on both sides are not unified, the CPU cannot calculate. At this time, our compiler will automatically convert the data on both sides of the operator into the same data type and then calculate it.

This method, which does not require manual conversion by the programmer but is automatically converted by the compiler, is called implicit conversion.

For example, the line of code 1 > "0" will not report an error in js. When using the operator, the compiler will first convert the "0" on the right into the number 0` and then compare the sizes.

Implicit conversion rules:

1. Convert to string type: + (string concatenation operator) 2. Convert to number type: ++/-- (increment and decrement operator) + - * / % (arithmetic operator) > < >= < = == != === !=== (relational operator)

2. Convert to boolean type: ! (logical NOT operator)

Example:​​​​​

console.log([] == []) // falseconsole.log([] == ![]) // trueconsole.log([] !== [])  // trueconsole.log(NaN != NaN) // trueconsole.log(null == undefined) // trueconsole.log(null === undefined) // falseconsole.log(1 == true) // trueconsole.log(null > 0) // falseconsole.log(true + 1) // 2console.log(undefined + 1) // NaNconsole.log({} + 1) // [object Object]1console.log([] + {}) // [object Object]console.log([2,3] + [1,2])  // 2,31,2

What is the difference between Object.is() and the original comparison operators "===", "=="?

(1) If two equal signs are equal, type conversion will be performed during comparison;

(2) Three equal signs are judged as equal (the judgment is strict), and implicit type conversion is not performed during comparison (false will be returned if the types are different);

(3) Object.is specially handles NaN, -0 and +0 on the basis of three equal signs, ensuring that -0 and +0 are no longer the same, but Object.is(NaN, NaN) will return true. Object.is should be considered to have its own special purpose and not to be considered more lenient or strict than other equality comparisons.

What is the difference between == and === in JS?

1. For basic types such as string and number, there is a difference between == and ===

1) Comparison between different types. == compares "values ​​converted into the same type" to see if the "values" are equal. === If the types are different, the result will be unequal.
2) Same type comparison, direct "value" comparison, the result will be the same.

2. For advanced types such as Array and Object, there is no difference between == and ===

Perform a "pointer address" comparison.

3. There is a difference between basic types and advanced types, == and ===

1) For ==, convert the advanced type into a basic type and perform "value" comparison.
2) Because the types are different, the result of === is false.

ES5 and ES6 have several ways to declare variables.

ES5 has two types: var and function

There are six types of ES6: four more, let, const, class and import

Note: Global variables declared by let, const, and class will no longer be linked to the properties of the global object.

What is an event proxy/event delegation?

Event proxy/event delegation uses the feature of event bubbling to bind events that should be bound to multiple elements to their ancestor elements. Especially when adding child elements dynamically, it can be very convenient to improve program performance. , reduce the memory space.

What is event bubbling? What is event capture?

Bubbling events: Events are triggered in order from the most specific event target to the least specific event target (document object).

Capture-type events: Events are triggered starting from the least precise object (document object) and then to the most precise (events can also be captured at the window level, but they must be specifically specified by the developer).

Use the addEventListener(event,fn,useCapture) method when adding an event. The third parameter useCapture in the base is a Boolean value, which is used to set whether the event is executed when the event is captured or when the event bubbles up.

Note: IE browser uses the attachEvent() method. This method has no relevant settings. However, IE's event model is executed when the event bubbles up by default, that is, when useCapture is equal to false, so useCapture is set when processing the event. It is safer to set it to false and also achieves browser compatibility.

How to stop events from bubbling up?

The w3c method is e.stopPropagation(), and IE uses e.cancelBubble = true. For example:​​​​​​​

window.event.cancelBubble = true;e.stopPropagation();

Return false can also prevent bubbling.

How to prevent default event?

The w3c method is e.preventDefault(), and IE uses e.returnValue = false, such as:​​​​​​​

function stopDefault( e ) {  if ( e && e.preventDefault )            e.preventDefault(); //IE中阻止函数器默认动作的方式   else             window.event.returnValue = false; }

Return false can also prevent the default behavior. 

What are the stages of DOM events? Let’s talk about the understanding of event agency

It is divided into three stages: capture stage - target stage - bubbling stage

To put it simply, the event proxy is: the event is not directly bound to an element, but to the parent element of the element. When the event is triggered (such as 'click'), the condition is judged to execute the event after the event is triggered. Statement (e.g. 'alert(e.target.innerhtml)')

Benefits: (1) Make the code more concise; (2) Save memory overhead

How to bind two onclick events to a button using native js?

Use addEventListener to bind multiple events. For example​​​​​​​

var btn = document.getElementById('btn')btn.addEventListener('click', fn1)btn.addEventListener('click', fn2)function fn1 () {
   
     console.log('我是方法1')  }function fn2 () {
   
     console.log('我是方法2')  }

What are the response events?

onclick mouse clicks an object; onfocus gets focus; onblur loses focus; onmousedown mouse is pressed, etc. Commonly used ones are as follows:

  1. Mouse click event (onclick)

  2. Mouse over event (onmouseover)

  3. Mouse move event (onmouseout)

  4. Cursor focus event (onfocus)

  5. Out of focus event ( onblur )

  6. Content selection event ( onselect )

  7. Text box content change event (onchange)

  8. Loading event ( onload )

  9. Unload event ( onunload )

The concept of closure? Advantages and Disadvantages? scenes to be used?

The concept of closure: A closure is a function that can read the internal variables of other functions.

  1. Avoid pollution of global variables

  2. Want a variable to be stored in memory for a long time (cache variable)

shortcoming:

  1. Memory leak (consumption)

  2. Resident memory, increases memory usage

Usage scenarios: When encapsulating functions (private properties and methods need to be used), function anti-shake, function throttling, function currying, and adding events to element pseudo-arrays need to use the index value of the element.

Causes of memory leaks

  1. Unexpected global variable (variable not declared using var inside the function)

  2. console.log

  3. Closure

  4. Object circular reference

  5. Uncleared timer

  6. DOM leak (after obtaining the DOM node, delete the DOM node, but do not manually release the variable, and the corresponding DOM node can still be accessed in the variable, which will cause leakage)

What exactly does the new operator do?

1) Create an empty object, and the this variable refers to the object, and also inherits the prototype of the function.

2) Properties and methods are added to the object referenced by this.

3) The newly created object is referenced by this, and finally this is returned implicitly.

The pointer of this in javascript

this always points to the object where the function is running, not the object where the function is created.

For ordinary function calls, this is whoever calls the function.

As for the constructor, if it is called directly without the new operator, then this will point to the window. After using the new operator to generate an object instance, this points to the newly generated object.

Anonymous functions or functions that are not in any object point to window.

If it is call, apply, etc., whoever this is specified is.

Let’s talk about the understanding of this

1) this always points to the direct caller of the function (not the indirect caller)

2) If there is the new keyword, this points to the object that comes out of new

3) In the event, this points to the target element. The special thing is that this in IE's attachEvent always points to the global object window.

What does eval do?

Its function is to parse the corresponding string into JS code and run it; you should avoid using eval, which is unsafe and very performance-consuming (twice, once to parse into a JS statement and once to execute).

The difference between call, apply and bind

call apply bind can change the this pointer of the function call. ​​​​​​​

函数.call(对象,arg1,arg2....)函数.apply(对象,[arg1,arg2,...])var ss=函数.bind(对象,arg1,arg2,....)

1. The first parameter specifies the point of this inside the function (the scope in which the function is executed), and then calls the function according to the specified scope.

2. You can pass parameters when calling the function. The call and bind methods need to be passed in directly, while the apply method needs to be passed in in the form of an array.

3. The call and apply methods execute the function immediately after the call, while the bind method does not execute immediately and the function needs to be executed again.

4. Changing the pointing of this object not only involves the call, apply, and bind methods, but you can also use the that variable to fix the pointing of this.

Javascript scope chain

The principle of the scope chain is very similar to the prototype chain. If the variable is not in its own scope, then it will look for the parent until the top level.

Note: JS does not have a block-level scope. To form a block-level scope, it can be implemented through (function(){})(); in the form of immediate execution.

Javascript prototype chain

First understand three concepts:

  • Prototype: Prototype object. Each function has a prototype attribute. When the object is instanced through the new command, this attribute will become the prototype object of the instance.

  • constructor: constructor. constructor pointing to the prototype object

  • __proto__: prototype of the instance object

In JavaScript, the link between the instance object and the prototype is called the prototype chain. When the Javascript parsing engine reads the value of an Object property, it will search upward along the prototype chain. If it is not found in the end, the property value is undefined; if the property value is finally found, the result is returned.

Inheritance (6 ways) and pros and cons

1. Prototype chain inheritance

2. Constructor inheritance

3. Combined inheritance (prototype chain inheritance + constructor inheritance)

4. Prototypal inheritance

5. Parasitic inheritance

6. Combination parasitic inheritance

Code example:​​​​​​​

//借助构造函数实现继承:缺点是父构造函数的原型链继承不了,若要全部继承除非将所有属性和方法定义在构造函数中function Parent1 () {
   
     this.name = 'parent1';}function Child1 () {
   
     //这么做的好处是定义在父构造函数中的引用类型的属性,对于子构造函数的每个实例来说是独立的  //并且在子构造函数实例化时,可以给父构造函数传参  Parent.call(this);  this.type = 'child1';}
//借助原型链实现继承:缺点是继承的引用类型属性是共享的,子构造函数的实例更改会影响其他实例上的这个属性,比如 play 属性function Parent2 () {
   
     this.name = 'parent2';  this.play = [1, 2, 3];}function Child2 () {
   
     this.type = 'Child2';}Child2.prototype = new Parent2();
//组合方式:缺点是会执行两次父构造函数function Child3 () {
   
     //执行第一次  Parent2.call(this);  this.type = 'Child3';}Child3.prototype = new Parent2(); //执行第二次
//组合优化1,不需要再将定义在父构造函数中的属性和方法再继承一次,只需要继承原型链上的Child3.prototype = Parent2.prototype;//缺点是无法区分一个实例是子函构造函数实例化的还是父构造函数实例化的let s1 = new Child3();//s1.constructor 指向了 Parent2,而不是 Child3,因为 Child3 原型对象的属性 constructor 继承了 Parent2 原型对象上的//如果你强行执行 Child3.prototype.constructor = Child3 的话,也会将 Parent2.prototype.constructor 改成 Child3
//组合优化2,通过 Object.create() 创建一个中间对象,将两个原型对象区别开来,并且继承父构造函数的原型链Child3.prototype = Object.create(Parent2.prototype);Child3.prototype.constructor = Child3;//即 Child3.prototype.__proto__ === Parent2.prototype 为 true//如此 Child3.prototype 和 Parent2.prototype 被隔离开,是两个对象,不会相互影响//这种方式为理想继承方式

Please explain variable declaration hoisting

Variables declared with var are promoted to the top of the scope. Not only variables, but function declarations are also hoisted.

When both variable and function declaration hoisting occurs in the same scope, the variable still precedes the function.

What is the difference between function declaration and function expression?

In Javscript, when the parser loads data into the execution environment, function declarations and function expressions are not treated equally. The parser will first read the function declaration and make it available (accessible) before executing any code. As for the function expression, it must wait until the parser reaches the line of code where it is located before it is actually parsed and executed.

What is a window object? What is a document object?

The window object represents a window opened in the browser. The document object represents the entire html document. In fact, the document object is a property of the window object.

The difference between document.onload and document.ready events

There are two events when the page is loaded. One is ready, which indicates that the document structure has been loaded (excluding non-text media files such as images). The other is onload, which indicates that all elements of the page including images and other files have been loaded.

Shallow copy and deep copy of Js

Shallow copy only copies the pointer to an object, not the object itself. The old and new objects still share the same memory. However, deep copy will create an identical object. The new object does not share memory with the original object, and modifications to the new object will not change the original object.

Shallow copy

// 第一层为深拷贝
Object.assign()
Array.prototype.slice()
扩展运算符 ...

deep copy

JSON.parse(JSON.stringify())

recursive function

function cloneObject(obj) {
  var newObj = {} //如果不是引用类型,直接返回
  if (typeof obj !== 'object') {
    return obj
  }
  //如果是引用类型,遍历属性
  else {
    for (var attr in obj) {
      //如果某个属性还是引用类型,递归调用
      newObj[attr] = cloneObject(obj[attr])
    }
  }
  return newObj
}

What exactly are arguments in JavaScript?

Each function in Javascript China will have an Arguments object instance arguments, which refers to the actual parameters of the function. You can use the array subscript "[]" to refer to the elements of arguments. arguments.length is the number of actual parameters of the function, and arguments.callee refers to the function itself.
In function code, using the special object arguments, developers do not need to explicitly indicate the parameter name, and can access the corresponding parameters by using subscripts.

function test() { 
 var s = ""; 
 for (var i = 0; i < arguments.length; i++) { 
  alert(arguments[i]);             
  s += arguments[i] + ","; 
 }
 return s; 
} 
test("name", "age");//name,age 

Although arguments has some array properties, it is not a real array, but an array-like object. It does not have many methods of arrays, and cannot call .jion(), .concat(), .pop() and other methods like a real array.

What is "use strict";? What are the advantages and disadvantages of using it?

The occurrence of the expression - "use strict"; in the code means that the code is parsed according to strict mode, which makes Javascript run under stricter conditions.

benefit:

  • Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors;

  • Eliminate some unsafe aspects of code operation and ensure the safety of code operation;

  • Improve compiler efficiency and increase running speed;

  • Pave the way for new versions of Javascript in the future.

harm:

  • The same code may have different running results in "strict mode";

  • Some statements that can run in "normal mode" will not run in "strict mode".

What is cross-domain? Is there any way to solve the problems caused by cross-domain?

Cross-domain needs to be understood based on the browser's same-origin policy. The same-origin policy means that the request must be for the same port, the same protocol, the same domain name, and client scripts from different sources cannot read without explicit authorization. Write each other's resources.
Affected by the browser's same-origin policy, scripts that are not from the same origin cannot operate objects from other sources. If you want to operate objects from another source, you need to cross domain.

Common solutions:

  • Cross-Origin Resource Sharing (CORS)

  • nginx proxy cross domain

  • nodejs middleware proxy cross domain

  • jsonp cross domain

Explain what Json is

(1)JSON is a lightweight data exchange format.

(2) JSON is language and platform independent, and JSON parsers and JSON libraries support many different programming languages.

(3) The syntax of JSON represents three types of values, simple values ​​(strings, numeric values, Boolean values, null), arrays, and objects

Explain the principle of jsonp and why it is not real ajax

Json is implemented by dynamically creating script tags and callback functions, while Ajax is a data operation without page refresh request.

Implementation of native Js:

(function (window,document) {
    "use strict";
    var jsonp = function (url,data,callback) {
        // 1.将传入的data数据转化为url字符串形式
        // {id:1,name:'fly63'} => id=1&name=fly63
        var dataString = url.indexof('?') == -1? '?': '&';
        for(var key in data){
            dataString += key + '=' + data[key] + '&';
        };
        // 2 处理url中的回调函数
        // cbFuncName回调函数的名字 :my_json_cb_名字的前缀 + 随机数(把小数点去掉)
        var cbFuncName = 'my_json_cb_' + Math.random().toString().replace('.','');
        dataString += 'callback=' + cbFuncName;
        // 3.创建一个script标签并插入到页面中
        var scriptEle = document.createElement('script');
        scriptEle.src = url + dataString;
        // 4.挂载回调函数
        window[cbFuncName] = function (data) {
            callback(data);
            // 处理完回调函数的数据之后,删除jsonp的script标签
            document.body.removeChild(scriptEle);
        }
        // 5.append到页面中
        document.body.appendChild(scriptEle);
    }
    window.$jsonp = jsonp;// 因为jsonp是一个私有函数外部不能调用,所有jsonp函数作文window对象的一个方法,供外部调用
})(window,document)

Let’s talk about the disadvantages of cookies?

(1) Limitation on the number and length of cookies. Each domain can only have a maximum of 20 cookies, and the length of each cookie cannot exceed 4KB, otherwise it will be truncated.

(2) Safety issues. If the cookie is intercepted by someone, that person can obtain all session information. Even encryption will not help, because the interceptor does not need to know the meaning of the cookie, he can achieve the purpose by simply forwarding the cookie as it is.

(3) Some states cannot be saved on the client. For example, to prevent duplicate form submissions, we need to save a counter on the server side. If we save this counter on the client side, it will have no effect.

What is cookie isolation? (Or: How to do not bring cookies when requesting resources)

By using multiple non-primary domain names to request static files, if the static files are placed under the primary domain name, it is very wasteful to submit the cookie data contained in the static file request to the server, and it is better to isolate them. Because cookies have domain restrictions, requests cannot be submitted across domains. Therefore, when using a non-primary domain name, the request header will not contain cookie data. This can reduce the size of the request header, reduce the request time, and thus reduce the overall request. purpose of delay. At the same time, this method does not pass the cookie to the server, but also reduces the server's processing and analysis of cookies, and improves the parsing speed of the server's http request.

Describe the differences between cookies, sessionStorage and localStorage?

sessionStorage and localStorage are provided by the HTML5 Web Storage API, which can easily save data between web requests. With local data, you can avoid unnecessary transfer of data back and forth between the browser and the server. sessionStorage, localStorage, and cookies are all data stored on the browser side. The concept of sessionStorage is very special and introduces the concept of a "browser window". sessionStorage is data that always exists in the same window (or tab) of the same origin. That is to say, as long as the browser window is not closed, the data will still exist even if the page is refreshed or another page from the same source is entered. After closing the window, sessionStorage is destroyed. Different windows opened "independently" at the same time, even if they are on the same page, the sessionStorage objects are different cookies and will be sent to the server. The other two won't. Microsoft noted that Internet Explorer 8 increased the cookie limit to 50 cookies per domain, but IE7 also appears to allow 50 cookies per domain.

  • Firefox has a cookie limit of 50 per domain name.

  • Opera has a cookie limit of 30 per domain name.

  • Firefox and Safari allow cookies to be up to 4097 bytes, including name, value and equal sign.

  • Opera allows cookies to be up to 4096 bytes, including: name, value and equal sign.

  • Internet Explorer allows cookies to be up to 4095 bytes, including: name, value and equal sign.

 

When localstorage cannot be deleted manually, when will it expire?

Unless cleared, clear() can be cleared permanently by clear()

sessionStorage is only valid in the current session and will be cleared after closing the page or browser.

 

What is function currying

Function currying is a technique that transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns a result.

The purpose of currying is to reduce code redundancy and increase code readability. Let’s look at a classic example related to currying:

// 实现一个add方法,使计算结果能够满足类似如下的预期:
// add(1)(2)(3) = 6;
// add(1, 2, 3)(4) = 10;
// add(1)(2)(3)(4)(5) = 15;
var add_currying=function(...rest){
  var sum=0;
  for(let item of rest){
   sum+=item;
  }
  var add_back = (...rest) => {
    for(let item of rest){
      sum+=item;
    }
    return add_back;
 };
 add_back.toString = () => sum;
 return add_back;
}
console.log(add_currying(1,2,3)); //6
console.log(add_currying(1,2)(3,4)); //10
console.log(add_currying(1,2)(3)(4,5)); //15
console.log(add_currying(1)(2)(3)(4)(5)(6)); //21
//打印出来会自动使用toString,即使是写var a=add_currying(1,2,3)也会自动调用此方法(默认将函数语句以字符串打出)
//而为了打印出我们想要的结果我们就需要自己重写toString方法
//如果不用es6的三点运算符就只能使用以前的Array.prototype.slice.call(arguments)方法

How does js handle anti-shake and throttling?

When performing operations such as window resize, scroll, and input box content verification, if the frequency of event processing function calls is unlimited, it will increase the burden on the browser and lead to a very poor user experience.
At this time, we can use debounce (anti-shake) and throttle (throttle) to reduce the call frequency without affecting the actual effect.

Function debounce:

When an event is continuously triggered, the event processing function will only be executed once if no event is triggered again within a certain period of time. If the event is triggered again before the set time arrives, the delay will be restarted.
As shown below, when the scroll event is continuously triggered, the handle function is not executed. When the scroll event is not triggered within 1000 milliseconds, the scroll event will be triggered with a delay.

function debounce(fn, wait) { 
 var timeout = null; 
 return function() { 
  if(timeout !== null) clearTimeout(timeout);           
  timeout = setTimeout(fn, wait); 
 } 
} 
// 处理函数 
function handle() {      
 console.log(Math.random()); 
} 
// 滚动事件
window.addEventListener('scroll', debounce(handle, 1000)); 函数节流

Function throttling:

When an event is continuously triggered, it is guaranteed that the event processing function is only called once within a certain period of time.
The popular explanation of throttling is like when we put water into the faucet. When the valve is opened, the water flows down. Adhering to the fine traditional virtues of diligence and thrift, we have to turn down the faucet. It is best to turn the faucet smaller according to our intention and according to certain rules. Drop by drop within a time interval.
As shown below, when the scroll event is continuously triggered, the handle function is not executed immediately, but is executed every 1000 milliseconds. ​​​​​​​

var throttle =function(func, delay) {  var prev = Date.now();  return function() {   var context = this;  var args = arguments;   var now = Date.now();   if (now - prev >= delay) {    func.apply(context, args);                              prev = Date.now();  }  } }function handle() {               console.log(Math.random()); }         window.addEventListener('scroll', throttle(handle, 1000)); 

What is the garbage collection mechanism in JS, which one is commonly used, and how is it handled?

The garbage collection mechanism of JS is to prevent memory leaks. The meaning of memory leaks is that a certain piece of memory still exists when it is no longer needed. The garbage collection mechanism is to find variables that are no longer used intermittently and irregularly, and Release the memory they point to.
The most common garbage collection method in JS is mark-and-sweep.
Working principle: When a variable enters the environment, the variable is marked as "entering the environment". When a variable leaves the environment, it is marked as "leaving the environment". The memory marked "leaving the environment" is recycled.

work process:

  1. The garbage collector will mark all variables stored in memory when it runs.

  2. Remove the tags of variables in the environment and variables referenced by variables in the environment.

  3. Variables that are marked again are considered variables to be deleted.

  4. The garbage collector completes the memory cleanup work, destroying those marked values ​​and reclaiming the memory space they occupy.

Those operations will cause memory leaks

When global variables, closures, and DOM are cleared or deleted, events are not cleared and child elements have references.

What is virtual DOM

The Document Object Model, or DOM, defines an interface that allows languages ​​such as JavaScript to access and manipulate HTML documents. Elements are represented by nodes in the tree, and interfaces allow us to manipulate them. But this interface comes at a cost, and a large number of very frequent DOM operations can slow down the page.

Vue solves this problem by implementing a virtual representation of the document structure in memory, where virtual nodes (VNode) represent nodes in the DOM tree. When manipulation is required, calculations and operations can be performed in the virtual DOM's memory rather than on the real DOM. This is naturally faster and allows the virtual DOM algorithm to calculate the most optimized way to update the actual DOM structure.

Once calculated, it is applied to the actual DOM tree, which improves performance, which is why virtual DOM-based frameworks such as vue and react are so prominent.

Ajax usage

The so-called asynchronous means that when sending a request to the server, we do not have to wait for the result, but can do other things at the same time. When the result is available, it will perform subsequent operations according to the settings. At the same time, the page will not be full page. Refreshed and improved user experience.
The process of creating Ajax:
1) Create XMLHttpRequest object (asynchronous calling object)

var xhr = new XMLHttpRequest();

2) Create a new HTTP request (method, URL, asynchronous or not)

xhr.open(‘get’,’example.php’,false);

3) Set up a function that responds to HTTP request status changes.
The readyState attribute in the onreadystatechange event is equal to 4. The response HTTP status is 200 (OK) or 304 (Not Modified).
4) Send http request

xhr.send(data);

5) Obtain the data returned by the asynchronous call.
Note:
1) When the page is loaded for the first time, try to output all relevant data at one time on the web server. Only after the page is loaded, the user uses ajax to interact when operating.
2) Synchronous ajax will cause the page to freeze on IE. So it is recommended to use asynchronous ajax.
3) Minimize the number of ajax requests.
4) Ajax security issues. Sensitive data should be processed on the server side to avoid filtering on the client side. Key business logic codes must also be processed on the server side.

Ajax native writing method

function ajax() {
	//创建一个 XHR 对象
	let oAjax = window.XMLHttpRequest ? (new XMLHttpRequest()) : (new window.ActiveXobject('Microsoft.XMLHTTP'));
	//返回一个函数,这是函数柯里化操作,不用每次调用 ajax 都判断浏览器环境
	//但是会占用更多的内存,因为总是会保存外部函数的作用域
	return function(url, fnSucc, fnFaild) {
		//只要 XHR 对象的 readyState 属性的值发生改变,就触发这个事件
		oAjax.onreadystatechange = function() {
			// readyState 属性是 0-4 的值,当为 4 时,表示已经接收到全部响应数据,并可以在客户端使用
			if (oAjax.readyState === 4) {
				//响应的 HTTP 状态
				let s = oAjax.status;
				if (s === 200 || s === 206 || s === 304) {
					//将响应主体被返回的文本作为参数传给这个函数,并执行这个函数
					if (fnSucc) fnSucc(oAjax.responseText);
				} else {
					if (fnFaild) fnFaild(oAjax.status);
				}
			}
		};
		//启动一个请求,准备发送
		oAjax.open('GET', url, true);
		//发送请求
		oAjax.send(null);
	}
}

The difference between get and post methods when making ajax requests

The most intuitive difference is that GET includes parameters in the URL, and POST passes parameters through the request body.

  • GET is harmless when the browser rolls back, while POST submits the request again.

  • The URL address generated by GET can be Bookmarked, but POST cannot.

  • GET requests will be actively cached by the browser, but POST will not unless manually set.

  • GET requests can only be URL encoded, while POST supports multiple encoding methods.

  • GET request parameters will be completely retained in the browser history, while parameters in POST will not be retained.

  • There is a length limit on the parameters transmitted in the URL of the GET request, but there is no limit on the length of the POST request.

  • Regarding the data type of parameters, GET only accepts ASCII characters, while POST has no restrictions.

  • GET is less secure than POST because the parameters are exposed directly on the URL, so it cannot be used to pass sensitive information.

  • GET parameters are passed through the URL, and POST is placed in the Request body.

In Javascript, when searching for objects during execution, the prototype function will never be searched?

Object.hasOwnProperty(proName): is used to determine whether an object has a property with the name you give it. However, it should be noted that this method cannot check whether the object has the property in the prototype chain. The property must be a member of the object itself.

What are the ways to lazy load JS?

Lazy loading of JS helps improve page loading speed.

defer and async, dynamic creation of DOM (most commonly used), asynchronous loading of JS on demand

defer: Delay script. Download immediately, but delay execution (delay until the entire page is parsed before running), and execute the scripts in the order they appear.
async: asynchronous script. It will be executed immediately after downloading, but it is not guaranteed to be executed in the order in which the scripts appear.

What is the difference between synchronous and asynchronous?

The concept of synchronization is in the operating system: different processes collaborate to complete a certain task and the order is adjusted (through blocking, waking up, etc.). Synchronization emphasizes sequence, who comes first and who comes last. There is no sequentiality in asynchronous.

Synchronization: The browser accesses the server, the user sees the page refreshed, and resends the request. After the request is completed, the page refreshes, new content appears, and the user proceeds to the next step after seeing the new content.
Asynchronous: The browser accesses the server request, the user operates normally, and the browser makes the request on the backend. When the request is completed, the page will not be refreshed, new content will appear, and the user will see the new content.

What should I do if the page encoding and the requested resource encoding are inconsistent?

If the requested resource encoding is different from the page encoding, such as the encoding of the external js file. It can be defined as charset="utf-8" or "gbk" according to the encoding method of the external resource.

For example: http://www.fly63.com/a.html has a http://www.fly63.com/test.js embedded in it.

The encoding of a.html is gbk or gb2312. The imported js encoding is utf-8, so you need to

<script src="http://www.fly63.com/test.js" charset="utf-8"></script>

How to do modular development?

Modular development refers to systematically decomposing the problem according to a classification thinking when solving a complex problem or a series of problems.

Modularization is a way of decomposing complex systems into manageable modules with a more reasonable code structure and higher maintainability. For the software industry: the system is decomposed into a set of highly cohesive, low-coupling modules.

(1) Define encapsulated modules
(2) Define the dependencies of new modules on other modules
(3) Support the introduction of other modules. Specifications for non-traditional module development methods have emerged in JavaScript. CommonJS module specifications, AMD (Asynchronous Module Definition), CMD (Common Module Definition), etc. AMD is an asynchronous module definition, all modules will be loaded asynchronously, and module loading will not affect the execution of subsequent statements.

What is the difference between AMD and CMD specifications?

AMD is the standardized output of module definitions during the promotion process of RequireJS. CMD is the standardized output of module definition during the promotion process of SeaJS. the difference:

  1. 1) For dependent modules, AMD is executed in advance and CMD is executed delayed. However, starting from RequireJS 2.0, it has also been changed to allow delayed execution (the processing methods are different depending on the writing method).

  2. 2) CMD promotes dependence on the nearest location, while AMD promotes dependence on the front.

  3. 3) AMD's API defaults to one being used for multiple purposes, while CMD's API is strictly differentiated and advocates single responsibility.

Explain page reflow and redraw

When part (or all) of the render tree needs to be rebuilt due to changes in the size, layout, hiding, etc. of the elements. This is called reflow.

Each page requires at least one reflow, which is when the page is loaded for the first time. Reflow will definitely occur at this time because the render tree needs to be built.

During reflow, the browser will invalidate the affected part of the rendering tree and reconstruct this part of the rendering tree. After completing the reflow, the browser will redraw the affected part to the screen. This process is called redrawing.

When some elements in the render tree need to update attributes, these attributes only affect the appearance and style of the elements, but will not affect the layout, such as background-color. It is called redrawing.

the difference:

Reflow will definitely cause a redraw, but redraw will not necessarily cause a reflow. For example: only when the color changes, redrawing will only occur and will not cause reflow.

Reflow is required when the page layout and geometric properties change, such as: adding or removing visible DOM elements, element position changes, element size changes - margins, padding, borders, width and height, content changes

Browser scroll distance

The distance between the viewable area and the top of the page

var scrollTop=document.documentElement.scrollTop||document.body.scrollTop

The size of the viewing area

(1)innerXXX (not compatible with ie)

window.innerHeight The height of the visual area, including the width of the scroll bar
window.innerWidth The width of the visual area, including the width of the scroll bar

(2)document.documentElement.clientXXX (compatible with IE)

document.documentElement.clientWidth The width of the visual area, excluding the width of the scroll bar
document.documentElement.clientHeight The height of the visual area, excluding the width of the scroll bar

How many types of nodes are there? What are they?

(1)Element node: nodeType ===1;

(2) Text node: nodeType ===3;

(3)Attribute node: nodeType ===2;

The difference between innerHTML and outerHTML

innerHTML (content contained within the element)

outerHTML (self and the content within the element)

The difference between document.write and innerHTML

document.write writes the content to the page and clears it to replace the original content, which will cause redrawing.

document.innerHTML writes content to a Dom node without redrawing

The difference between offsetWidth offsetHeight and clientWidth clientHeight

(1)offsetWidth (content width + padding width + border width)
(2) offsetHeight (content height + padding height + border height)
(3) clientWidth (content width + padding width)
(4) clientHeight (content height + padding height)

DOM manipulation

(1) Create a new node

createDocumentFragment() //Create a DOM fragment
createElement() //Create a specific element
createTextNode() //Create a text node

(2) Add, remove, replace, insert

appendChild()
removeChild()
replaceChild()
insertBefore() //Insert a new child node before the existing child node

(3) Search

getElementsByTagName() //Through the tag name
getElementsByName() //Through the value of the Name attribute of the element (IE has strong fault tolerance, you will get an array, including the id equal to the name value)
getElementById() //Through the element Id, unique sex

The relationship between BOM and DOM

The full name of BOM is Browser Object Model, which is the browser object model, which mainly deals with browser windows and frames.

The full name of DOM is Document Object Model, which is the application programming interface (API) of HTML and XML. It follows the W3C standard and is a standard that all browsers abide by.

JS accesses, controls, and modifies the client (browser) by accessing the BOM (Browser Object Model) object. Since the window of the BOM contains the document, the properties and methods of the window object can be directly used and perceived, so it can be directly Using the document attribute of the window object, you can access, retrieve, and modify the content and structure of the XHTML document through the document attribute. Because the document object is the root node of the DOM.

It can be said that BOM contains DOM (object). What the browser provides for access is the BOM object. From the BOM object to the DOM object, js can operate the browser and the documents read by the browser.

What are the native methods of array objects? Let’s list them.

pop、push、shift、unshift、splice、reverse、sort、concat、join、slice、toString、indexOf、lastIndexOf、reduce、reduceRight、forEach、map、filter、every、some

pop: delete and return the last element of the array (change the original array);
push: return the length of the array after addition (change the original array);
shift: remove and return the first element of the array (change the original array);
unshift : Insert an element slice at the head of the array
: slice (subscript, number) returns the trimmed array (without changing the original array);
splice: inserts, deletes or replaces elements of the array
concat: merges the arrays and returns the combined array (without changing the original array) original array);
join: link the array into a string using identifiers and return the spliced ​​string (without changing the original array);
reverse: flip the array (change the original array);
toString: convert the array into a string;
split: Split the string and store it in an array;
forEach: mainly used to traverse the array;
every: mainly used to check whether each element in the array meets the conditions of the function, if one of them does not meet the conditions, return false;
indexOf: mainly Used to find elements in an array and return the position of the element.

String methods

charAt(): Find the corresponding value based on the subscript

charCodeAt(): Find the corresponding character Unicode encoding through the subscript value

indexOf(): Find the corresponding subscript by character (first occurrence)

lastIndexOf(): Find the last subscript value that appears through characters

slice(): intercept string, 2 parameters, (starting position, ending position)

split(): Split the string into arrays according to the delimiter

substring(): intercept string, (starting position, ending position)

substr(): intercept the string at the specified position and length, (starting position, length)

toLowerCase(): Convert string to lowercase

toUpperCase(): Convert string to uppercase

trim(): remove all spaces before and after the string

What is the difference between Array.splice() and Array.slice() methods in JS

Without further ado, let’s look at the first example:​​​​​​​

var arr=[0,1,2,3,4,5,6,7,8,9];//设置一个数组console.log(arr.slice(2,7));//2,3,4,5,6console.log(arr.splice(2,7));//2,3,4,5,6,7,8//由此我们简单推测数量两个函数参数的意义,slice(start,end)第一个参数表示开始位置,第二个表示截取到的位置(不包含该位置)splice(start,length)第一个参数开始位置,第二个参数截取长度

Then look at the second one:​​​​​​​

var x=y=[0,1,2,3,4,5,6,7,8,9]console.log(x.slice(2,5));//2,3,4console.log(x);[0,1,2,3,4,5,6,7,8,9]原数组并未改变//接下来用同样方式测试spliceconsole.log(y.splice(2,5));//2,3,4,5,6console.log(y);//[0,1,7,8,9]显示原数组中的数值被剔除掉了

Although slice and splice both intercept array objects, there are still obvious differences between them. The first parameter of slice and splice in the function parameters is the starting position of interception, and the second parameter of slice is the end position of interception (not included). , and the second parameter of splice (indicating the length of the interception from the starting position), slice will not change the original array, and splice will directly eliminate the intercepted data in the original array!

How to dynamically add/remove properties of an object in JS?

We can use object.property_name = value to add properties to the object, and delete object.property_name is used to delete properties.

For example:​​​​​​​

let user = new Object();// adding a propertyuser.name='Anil';user.age  =25;console.log(user);delete user.age;console.log(user);

Lazy loading and preloading of images

Preloading: New Image(); is commonly used, set its src to implement preloading, and then use the onload method to call back the preloading completion event. ​​​​​​​

function loadImage(url, callback){
   
       var img = new Image(); //创建一个Image对象,实现图片预下载    img.src = url;    if (img.complete){
   
            // 如果图片已经存在于浏览器缓存,直接调用回调函数        callback.call(img);        return; // 直接返回,不用再处理onload事件    }    img.onload = function (){
   
       //图片下载完毕时异步调用callback函数。    callback.call(img);//将回调函数的this替换为Image对象 ,如果你直接用img.width的时候,图片还没有完全下载下来    };}

Lazy loading: The main purpose is to optimize the server front-end, relieve the pressure on the server front-end, reduce the number of one-time requests or delay requests. Implementation method:
1. The first is pure delayed loading, using setTimeOut and setInterval to delay loading.
2. The second is conditional loading, which starts asynchronous downloading only when certain conditions are met or certain events are triggered.
3. The third method is to load the visual area, that is, only load the area that the user can see. This is mainly achieved by monitoring the scroll bar. Generally, it will start loading at a certain distance before the user sees a picture, which can ensure that the user You can just see the picture when you pull it down.

What is a callback

A callback function is a normal JS function passed to a method as a parameter or option. It is a function that is executed after another function has finished executing, hence it is called a callback.

In JS, functions are objects, therefore, functions can accept functions as parameters and can be returned by other functions.

What is the difference between host objects and native objects in JS?

Host objects: These are objects provided by the running environment. This means they are different in different contexts. For example, browsers contain objects like windows, but the Node.js environment provides objects like Node List.

Native objects: These are built-in objects in JS. They are also called global objects because built-in objects are not affected by the runtime environment if using JS.

Progressive enhancement and graceful degradation

Progressive enhancement: Build pages for low-version browsers to ensure the most basic functions, and then improve effects, interactions, etc. for advanced browsers to achieve a better user experience.

Graceful degradation: Build complete functionality from the beginning, and then make it compatible with lower version browsers.

Web Worker and Web Socket?

websocket: Provides full-duplex, two-way communication over a single persistent connection. Using custom protocols (ws://, wss://), the same-origin policy does not apply to web sockets.
web worker: JavaScript that runs in the background and does not affect the performance of the page.

Create a worker: var worker = new Worker(url);
Send data to the worker: worker.postMessage(data);
Receive data returned by the worker: worker.onmessage
Terminate the execution of a worker: worker.terminate();

browser thread

JS engine thread: interpret and execute JS code, user input, network requests, etc.

GUI thread (rendering thread): draws the user interface and is mutually exclusive with the JS main thread

HTTP network request thread: handles the user's GET, POST and other requests, and after getting the return result, pushes the callback function into the event queue

Timer trigger thread: setTimeout, setInterval waits for the end of the time, and pushes the execution function into the event queue.

Event processing thread: After interactive events such as click, mouse, and input occur, the event processing function is pushed into the event queue.

js execution mechanism, event loop

A major feature of the JavaScript language is that it is single-threaded and can only do one thing at a time. Single thread means that all tasks need to be queued, and the next task will not be executed until the previous task is completed. If the previous task takes a long time, the next task will have to wait.

The designers of the JavaScript language realized this problem and divided all tasks into two types, one is synchronous tasks (synchronous) and the other is asynchronous tasks (asynchronous). Before all synchronous tasks are executed, any asynchronous tasks will not be executed. will be implemented.

When we open a website, the rendering process of the web page is a lot of synchronized tasks, such as the rendering of page skeleton and page elements. Tasks that take up a lot of resources and take a long time, such as loading pictures and music, are asynchronous tasks.

JS asynchronous has a mechanism, which is to execute the macro task first and put the macro task into the Event Queue when encountering a macro task, and then execute the micro task and put the micro task into the Event Queue. However, these two Queues are not one Queue.

When you take it out, first get the callback function from the microtask, and then get the callback function of the macrotask from the Queue of the macrotask.

Macro task: overall code script, setTimeout, setInterval
Micro task: Promise, process.nextTick

Why does JS distinguish between microtasks and macrotasks?

(1) js is single-threaded, but divided into synchronous and asynchronous
(2) Microtasks and macrotasks are both asynchronous tasks, and they all belong to a queue
(3) Macrotasks are generally: script, setTimeout, setInterval, setImmediate
(4) Microtasks : Native Promise
(5) When encountering a microtask, execute the microtask first. After execution, if there is no microtask, execute the next macrotask. If there are microtasks, execute the microtasks one by one in order.

Ways to reduce page load time

  • Optimize images

  • Selection of image format (GIF: provides fewer colors and can be used in places where color requirements are not high)

  • Optimize css (compress and merge css, such as margin-top, margin-left...)

  • Add a slash after the URL (such as www.campr.com/directory, it will determine what file type this "directory is", or it is a directory.)

  • Indicate height and width (if the browser does not find these two parameters, it needs to calculate the size while downloading the image. If there are many images, the browser needs to constantly adjust the page. This not only affects the speed, but also affects the browsing experience. When the browser knows After setting the height and width parameters, even if the image cannot be displayed temporarily, the space for the image will be vacated on the page, and then the subsequent content will continue to be loaded. As a result, the loading time will be faster and the browsing experience will be better.)

  • Reduce http requests (merge files, merge pictures).

The difference between threads and processes

A program has at least one process, and a process has at least one thread. The division scale of threads is smaller than that of processes, making multi-threaded programs highly concurrency.

In addition, the process has an independent memory unit during execution, and multiple threads share memory, thus greatly improving the running efficiency of the program.

Threads are still different from processes during execution. Each independent thread has an entry point for program execution, a sequential execution sequence, and an exit point for the program.

However, threads cannot execute independently and must exist in the application program, and the application program provides multiple thread execution control.

From a logical point of view, the meaning of multi-threading is that in an application, multiple execution parts can be executed at the same time. However, the operating system does not regard multiple threads as multiple independent applications to implement process scheduling and management and resource allocation. This is the important difference between processes and threads.

Tell me about your understanding of semantics?

1. When the style is removed or lost, the page can present a clear structure: HTML itself has no performance. We see that for example, <h1> is bold, font size is 2em, bold; <strong> is bold, do not I think this is the performance of HTML. In fact, the default CSS styles of HTML are at work.

Therefore, when the style is removed or lost, it is not the advantage of the semantic HTML structure that the page can present a clear structure. However, browsers have default styles. The purpose of the default style is also to better express the semantics of html. It can be said that browsers The default styles and semantic HTML structure are inseparable.

2. Screen readers (if the visitor is visually impaired) will "read" your page based entirely on your markup.

3. Devices such as PDAs and mobile phones may not be able to render web pages like ordinary computer browsers (usually because these devices have weak support for CSS).

4. Conducive to SEO: Establishing good communication with search engines helps crawlers crawl more effective information: crawlers rely on tags to determine the context and weight of each keyword.

5. It is easier for team development and maintenance, and semantics are more readable. This is an important trend in the next step of web pages. Teams that follow W3C standards all follow this standard, which can reduce differentiation.

Why is it more efficient to use multiple domain names to serve website resources?

1. CDN caching is more convenient

2. Break through the browser concurrency limit (generally no more than 6 links are established per domain name)

3. Cookieless, saving bandwidth, especially uplink bandwidth is generally slower than downlink bandwidth

4. Isolate UGC content from the main site to prevent unnecessary security issues (uploading js to steal the main site’s cookies, etc.). It is for this reason that the domain name of user content must not be a subdomain name of the own main site, but a completely independent third-party domain name.

5. The data is divided and even divided into different physical clusters. It is easier to divert the data through subdomain names. This may not be used much.

PS: Regarding the issue of cookies, bandwidth is secondary, security isolation is primary. Regarding multiple domain names, more is not always better. Although the server can do general interpretation, it is time-consuming for the browser to do dns interpretation, and there are too many domain names. If you want to use https, you still have to buy more certificates and deploy them. .

How do you organize and optimize your code?

Internal: module mode; external: inheritance

code reuse

Avoid global variables (namespace, enclosed space, modular mvc...)

Split functions to avoid bloated functions

Comment

Front-end modularization and componentization

Modularization: reusable, focusing on functional encapsulation, mainly for Javascript code, isolating and organizing copied JavaScript code, and encapsulating it into modules with specific functions.

Componentization: Reusable, more attention is paid to the UI part. Each component of the page, such as the header, pop-up box and even the confirmation button, can become a component. Each component has independent HTML, css, and js codes.

HTTP cache mechanism and function?

Definition: Browser Caching is to speed up browsing. The browser stores recently requested documents on the user's disk. When the visitor requests this page again, the browser can display the document from the local disk, so that Can speed up page reading.
The role of cache:
1. Reduce delays, make your website faster, and improve user experience.
2. Avoid network congestion, reduce request volume, and reduce output bandwidth.
Implementation means:
max-age in Cache-Control is the main means to implement content cache. There are three common strategies: the combination of max-age and Last-Modified (If-Modified-Since), only max-age, max-age and ETag combination.

For forced caching, the server notifies the browser of a cache time. During the cache time, the next request will directly use the cache. If not within the time, a comparison cache policy will be executed.
For comparison caching, the Etag and Last-Modified in the cache information are sent to the server through the request, and are verified by the server. When a 304 status code is returned, the browser directly uses the cache.

Common HTTP status codes

400 The client request has a syntax error and cannot be understood by the server.
403 The server receives the request but refuses to provide the service. | 200
The client request is
successful
.
The server is currently unable to handle client requests and may return to normal after some time.

What are the main types of errors in JS?

There are three types of errors in JS:

Load-time errors: Errors (such as syntax errors) that occur when loading a web page are called load-time errors, which generate errors dynamically.

Runtime errors: Errors caused by misuse of commands in html language.

Logic Errors: These errors are caused by executing wrong logic on functions with different operations

List some design patterns in JS

Design patterns are general reusable solutions to common problems in software design. Here are some design patterns:

Creation pattern: This pattern abstracts the object instantiation process.

Structural Patterns: These patterns deal with different classes and objects to provide new functionality.

Behavioral model: Also called publish-subscribe model, it defines a one-to-many object relationship between an observer and multiple observers.

Parallel Design Patterns: These patterns deal with multi-threaded programming paradigms.

Architectural Design Patterns: These patterns are used to deal with architectural design.

New features of es6

  1. const let

  2. template string

  3. arrow function

  4. Function parameter default values

  5. Object and array destructuring

  6. for...of 和 for...in

Explain what is an arrow function?

Arrow functions are a concise way to write function expressions in ES6 or higher. Arrow functions cannot be used as constructors and do not support the this, arguments, super or new.target keywords. They are best suited for non-method functions. 

Typically, arrow functions look like const function_name = () => {}. ​​​​​​

const greet=()=>{console.log('hello');}greet();

The difference between ordinary functions and arrow functions

1. Ordinary functions
can change this pointer through bind, call, and apply.
New can be used
. 2. Arrow function
itself does not have this pointer.
Its this
is inherited from the ordinary function that inherits this from the first ordinary function in the outer layer when it is defined. When the this point of the arrow function changes, the this point of the arrow function will change accordingly.
When there is no ordinary function in the outer layer of the arrow function, the this point of the window cannot
be changed through bind, call, and apply. Calling
the arrow function with new will report an error because the arrow function does not have a constructor.

Explain what is a promise?

A promise is an object in js that is used to generate a value that may produce results in the future. The value can be a parsed value or a reason why the value was not parsed.

A promise can have three states:

pending: initial state, neither success nor failure
fulfilled: means the operation was completely successful
rejected: means the operation failed

A promise object in a waiting state can return a value after success or an error after failure. When these two situations occur, the processing function will be queued for execution and the then method will be called.

Resolve and reject are two functions respectively. When called in the callback, the state of the promise instance will be changed. resolve changes the state to success and reject to failure.

Handwritten promise

function Promise(exector) {
   
     let _this = this;  //status表示一种状态  let status = “pending“;  let value = undefined;  let reason = undefined;  //成功  function resolve(value) {
   
       if (status == “pending“) {
   
         _this.value = value;      _this.status = “resolve“;    }  }  //执行失败  function reject(value) {
   
       if (status == “pending“) {
   
         _this.value = value;      _this.status = “reject“    }  }  //异步操作  try {
   
       exector(resolve, reject)  } catch (e) {
   
       reject(e)  }  //测试then  Promise.prototype.then = function(reject, resolve) {
   
       let _this = this;    if (this.status == “resolve“) {
   
         reject(_this.value)    }    if (this.status == “reject“) {
   
         resolve(_this.reason)    }  }} //new Promise测试let promise = new Promise((reject,resolve)=>{
   
       resolve(“return resolve“);});promise.then(data => {
   
     console.log(`success${data}`);}, err => {
   
     console.log(`err${data}`);})

What is the difference between promise and async?

1. What is Async/Await?
Async/await is a new way of writing asynchronous code. The way it is used looks like synchronous
async/await is implemented based on Promise. It cannot be used for ordinary callback functions.
2. What is promise?
It is created to solve asynchronous nesting and make the code easier to understand.
The difference: async/await makes the code more synchronous and further optimizes the code.

Introduce various asynchronous solutions

(1) Callback function (asynchronous callback)

A callback is a function that is passed as a parameter to another function and then executed after that function has finished executing.

(2)promise 

The promise object is a specification and a pattern proposed by the commonJS working group to provide a unified interface for asynchronous programming.

(3)async/await

(4) Event monitoring

Adopt an event-driven model. The execution of a task does not depend on the order of the code, but on whether an event occurs.

(5) Publish/Subscribe

What is the difference between module.exports and exports?

Module and exports are two objects built into each js file by Node.js. It can be printed out through console.log(module) and console.log(exports). If you write the following two lines in main.js and then run $ node main.js:​​​​​​​

console.log(exports);//输出:{}console.log(module);//输出:Module {..., exports: {}, ...} (注:...代表省略了其他一些属性)

From printing, we can see that module.exports and exports are both empty objects {} at the beginning. In fact, these two objects point to the same memory. This means that module.exports and exports are equivalent (there is a premise: do not change the memory addresses they point to).

For example: exports.age = 18 and module.export.age = 18, these two writing methods are consistent (both are equivalent to adding an attribute to the original empty object {}, and the result obtained through require is {age: 18}) .

What are import and exports?

Import and exports help us write modular JS code. Using import and exports, we can split the code into multiple files. Import only allows access to certain specific variables or methods of the file. Methods or variables exported by a module can be imported. ​​​​​​​

 //index.js import name,age from './person';  console.log(name); console.log(age);
 //person.js let name ='Sharad', occupation='developer', age =26; export { name, age}; ​​​​​​​

Original link: Basic interview questions from JavaScript interview questions (with answers)

 

Guess you like

Origin blog.csdn.net/weixin_64948861/article/details/129271915