Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the perfect guide for Javascript interview?

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What is the perfect guide for Javascript interview? for this question, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

To illustrate the complexity of the JS interview, first, try the following results:

Onsole.log (2) = = new Boolean (true) = = "1")

Nine times out of ten, false will be given, but the result is actually true. See here for the reason.

1) understand JS function

Function is the essence of JavaScript and a first-class citizen of JS. The JS function is not just an ordinary function. Unlike other languages, the JS function can be assigned to a variable, passed as an argument to another function, or returned from another function.

Console.log (square (5)); / *... * / function square (n) {return n * n;}

Think the code is very simple, everyone should know how to print: 25. Then take a look at one:

Console.log (square (5)); var square = function (n) {return n * n;}

At first glance, you may be tempted to say that you also printed 25. But unfortunately, it will be wrong:

TypeError: square is not a function

In JavaScript, if a function is defined as a variable, the variable name is promoted and the JS executes until its definition can be accessed.

You may see the following code frequently in some code.

Var simpleLibrary = function () {var simpleLibrary = {a, b, add: function (a, b) {return a + b;}, subtract: function (a, b) {return a-b;}} return simpleLibrary;} ()

Why would you do such a strange thing? This is because variables and functions in a function variable are packaged separately to avoid global variable contamination. JQuery to Lodash libraries use this technology to provide $, _, etc.

2) understand bind, apply, and call

You may have seen these three functions in all the common libraries. They allow local application, and we can combine functions into different functions. A good js developer can tell you about these three functions at any time.

Basically, these are prototype ways to change behavior to achieve certain functions, and according to JS developer Chad, the usage is as follows:

If you want to call this function in a context, use .bind (), which is useful in events. If you want to call the function immediately, use .call () or .apply (), and modify the context.

Give examples to illustrate

Let's see what the above statement means! Suppose your math teacher asks you to create a library and submit it. You write an abstract library that works out the area and perimeter of a circle:

Var mathLib = {pi: 3.14, area: function (r) {return this.pi * r * r;}, circumference: function (r) {return 2 * this.pi * r;}}

After the submission, the teacher called it:

MathLib.area (2);

The teacher found that he asked for pi to be accurate to 5 decimal places and you were only accurate to 2 digits. Now you have no chance to submit the database because the deadline has passed. Here, the call function of JS can help you by calling your code as follows:

MathLib.area.call ({pi: 3.1.159}, 2)

It gets the new pi value dynamically, and the result is as follows:

12.56636

At this point, notice that the call function takes two parameters:

Context

Function parameter

In the area function, the context is that the object is replaced by the keyword this, and the following parameters are passed as function parameters. As follows:

Var cylinder = {pi: 3.14, volume: function (r, h) {return this.pi * r * h;}}

The calling method is as follows:

Cylinder.volume.call ({pi: 3.14159}, 2,6); 75.398159999999999

Apply is similar, except that function arguments are passed as an array.

Cylinder.volume.apply ({pi: 3.14159}, [2,6]); 75.39815999999999

If you can use call, you can basically use apply, and vice versa, what is the use of bind?

Bind injects a brand new this into the specified function, changing the direction of the this, and when using bind, the function will not be executed immediately like call or apply.

Var newVolume = cylinder.volume.bind ({pi: 3.14159}); newVolume (2mem6); / / Now pi is 3.14159

What is the purpose of bind? It allows us to inject context into a function that returns a new function with an update context. This means that this variable will be a user-supplied variable, which is useful when dealing with JavaScript events.

3) understand js scope (closure)

The scope of JavaScript is a Pandora's box. From this simple concept, hundreds of difficult interview questions can be constructed. There are three scopes:

Global scope

Local / function scope

Block-level scope (ES6 introduction)

Examples of global scope are as follows:

X = 10; function Foo () {console.log (x); / / Prints 10} Foo ()

Function scope takes effect when you define a local variable:

Pi = 3.14; function circumference (radius) {pi = 3.14159; console.log (2 * pi * radius); / / print "12.56636" is not "12.56"} circumference (2)

The ES16 standard introduces a new block scope that limits the scope of a variable to a given parenthesis block.

Var a = 10; function Foo () {if (true) {let a = 4;} alert (a); / / alerts' 10' because the 'let' keyword} Foo ()

Functions and conditions are treated as blocks. The above example should pop up 4 because if has been executed. But it is ES6 that destroys the scope of block-level variables, and the scope goes global.

Now to the magical scope, you can use closures, which are functions that return another function, the JavaScript closure.

If someone asks you this question, write an input string and return the characters one at a time. If a new string is given, the old string should be replaced, similar to a simple generator.

Function generator (input) {var index = 0; return {next: function () {if (index)

< input.lenght) { return input[index -1]; } return ""; } } } 执行如下: var mygenerator = generator("boomerang"); mygenerator.next(); // returns "b" mygenerator.next() // returns "o" mygenerator = generator("toon"); mygenerator.next(); // returns "t" 在这里,作用域扮演着重要的角色。闭包是返回另一个函数并携带数据的函数。上面的字符串生成器适用于闭包。index 在多个函数调用之间保留,定义的内部函数可以访问在父函数中定义的变量。这是一个不同的作用域。如果在第二级函数中再定义一个函数,它可以访问所有父级变量。 4) this (全局域、函数域、对象域) 在 JavaScript 中,我们总是用函数和对象编写代码, 如果使用浏览器,则在全局上下文中它引用 window 对象。 我的意思是,如果你现在打开浏览器控制台并输入以下代码,输出结果为 true。 this === window; 当程序的上下文和作用域发生变化时,this 也会发生相应的变化。现在观察 this 在一个局部上下文中: function Foo(){ console.log(this.a); } var food = {a: "Magical this"}; Foo.call(food); // food is this 思考一下,以下输出的是什么: function Foo(){ console.log(this); // 打印 {}? } 因为这是一个全局对象,记住,无论父作用域是什么,它都将由子作用域继承。打印出来是 window 对象。上面讨论的三个方法实际上用于设置这个对象。 现在,this 的***一个类型,在对象中的 this, 如下: var person = { name: "Stranger", age: 24, get identity() { return {who: this.name, howOld: this.age}; } } 上述使用了 getter 语法,这是一个可以作为变量调用的函数。 person.identity; // returns {who: "Stranger", howOld: 24} 此时,this 实际上是指对象本身。正如我们前面提到的,它在不同的地方有不同的表现。 5) 理解对象 (Object.freeze, Object.seal) 通常对象的格式如下: var marks = {physics: 98, maths:95, chemistry: 91}; 它是一个存储键、值对的映射。 javascript 对象有一个特殊的属性,可以将任何东西存储为一个值。这意味着我们可以将一个列表、另一个对象、一个函数等存储为一个值。 可以用如下方式来创建对象: var marks = {}; var marks = new Object(); 可以使用 JSON.stringify() 将一个对象转制成字符串,也可以用 JSON.parse 在将其转成对象。 // returns "{"physics":98,"maths":95,"chemistry":91}" JSON.stringify(marks); // Get object from string JSON.parse('{"physics":98,"maths":95,"chemistry":91}'); 使用 Object.keys 迭代对象: var highScere = 0; for (i of Object.keys(marks)) { if (marks[i] >

HighScore) highScore = marks [I];}

Object.values returns the value of the object as an array.

Other important functions on the object are

Object.prototype (object)

Object.freeze (function)

Object.seal (function)

Many application-related functions are provided on Object.prototype, as follows:

Object.prototype.hasOwnProperty is used to check whether a given property / key exists in the object.

Marks.hasOwnProperty ("physics"); / / returns true marks.hasOwnProperty ("greek"); / / returns false

Object.prototype.instanceof determines whether a given object is the type of a particular prototype.

Function Car (make, model, year) {this.make = make; this.model = model; this.year = year;} var newCar = newCar ('Honda',' City', 2007); console.log (newCar instanceof Car); / / returns true

Use Object.freeze to freeze an object so that its existing properties cannot be modified.

Var marks = {physics: 98, maths:95, chemistry: 91}; finalizedMarks = Object.freeze (marks); finalizedMarks ["physics"] = 86; / / throws error in strict mode console.log (marks); / / {physics: 98, maths:95, chemistry: 91}

Here, an attempt is made to modify the value of the frozen physics, but JavaScript does not allow this. We can use Object.isFrozen to determine whether a given object is frozen:

Object.isFrozen (finalizedMarks); / / returns true

Object.seal is slightly different from Object.freeze. The Object.seal () method closes an object, prevents new attributes from being added, and marks all existing properties as unconfigurable. The value of the current property can be changed as long as it is writable.

Var marks = {physics: 98, maths:95, chemistry: 91}; Object.seal (marks); delete marks.chemistry; / / returns false as operation failed marks.physics = 95; / / Works! Marks.greek = 86; / / Will not add a new property

Similarly, you can use Object.isSealed to determine whether an object is sealed.

Object.isSealed (marks); / / returns true

There are many other important functions / methods on global object functions, find them here.

6) understand prototype inheritance

In traditional JavaScript, there is a disguised concept of inheritance, which is implemented by using prototype technology. In ES5 and ES6, we can see that the syntax of using new is only the syntax sugar of the underlying prototype OOP. Creating a class is done using functions in JavaScript.

Var animalGroups = {MAMMAL: 1, REPTILE: 2, AMPHIBIAN: 3, INVERTEBRATE: 4}; function Animal (name, type) {this.name = name; this.type = type;} var dog = new Animal ("dog", animalGroups.MAMMAL); var crocodile = new Animal ("crocodile", animalGroups.REPTILE)

Here we create an object for the class (using the new keyword), and you can append methods to the class in the following ways:

Animal.prototype.shout = function () {console.log (this.name+'is'+this.sound+'ing...');}

You may have questions here. There is no sound property in the class. Yes, it is intended to be passed by a subclass that inherits the above class.

In JavaScript, the following implementation inherits:

Function Dog (name, type) {Animal.call (this, name, type); this.sound = 'bow';}

I defined a more specific function called Dog. Here, in order to inherit the Animal class, I need call to pass this and other parameters. Use the following ways to instantiate a German shepherd.

Var pet = Dog ("German Shepherd", animalGroups.MAMMAL); console.log (pet); / / returns Dog {name: "German Shepherd", type: 1, sound: "bow"}

Instead of assigning the name and type properties in the subfunction, we call the superfunction Animal and set the corresponding properties. Pet has properties of the parent class (name, type). But the method. Did they inherit it? Let's take a look:

Pet.shout (); / / Throws error

Why is this? This happens because JavaScript is not specified to inherit the parent class method. How to solve?

/ / Link prototype chains Dog.prototype = Object.create (Animal.prototype); var pet = new Dog ("germanShepard", animalGroups.MAMMAL); / / Now shout method is available pet.shout (); / / German Shepherd bowing...

You can now use the shout method. We can use the object.constructor function to check the class of a given object in JavaScript to see what class pet is:

Pet.constructor; / / returns Animal

This is vague, and Animal is a parent class. But what kind of pet is it? Pet should be the type of Dog. It is an Animal type because the constructor of the Dog class:

Dog.prototype.constructor; / / returns Animal

It is of type Animal. We should set it to Dog itself so that all instances (objects) of the class can give the correct class name.

Dog.prototype.constructor = Dog

With regard to prototype inheritance, we should keep the following in mind:

Class properties are bound using this

Class methods are bound using prototype objects

To inherit properties, use the call function to pass this

To inherit methods, use Object.create to connect parent and child prototypes

Always set the subclass constructor to itself to get the correct type of its object

7) understand callback and promise

A callback is a function that is executed after the Istroke O operation is completed. A time-consuming IUnip O operation blocks the code and is therefore not allowed in Python/Ruby. But in JavaScript, since asynchronous execution is allowed, we can provide callbacks to asynchronous functions. This example is a browser-to-server AJAX (XMLHettpRequest) call generated by mouse and keyboard events. As follows:

Function reqListener () {console.log (this.responseText);} var req = new XMLHttpRequest (); req.addEventListener ("load", reqListener); req.open ("GET", "http://www.example.org/example.txt"); req.send ())

The reqListener here is a callback function, which is executed when the GET request is successfully responded to.

Promise is an elegant wrapper of callback functions, which allows us to implement asynchronous code gracefully. A lot of promise is discussed in the following article, which is an important part of what you should know in JS.

8) understand regular expression

Regular expressions have many applications, such as dealing with text, enforcing rules on user input, and so on. JavaScript developers should know how to execute basic regular expressions and solve problems. Regex is a general concept, so let's see how you can do this from JS.

There are two ways to create regular expressions:

Var re = / ar/; var re = new RegExp ('ar')

The regular expression above is an expression that matches a given set of strings. After defining the regular expression, we can try to match and view the matching string. You can use the exec function to match strings:

Re.exec ("car"); / / returns ["ar", index: 1, input: "car"] re.exec ("cab"); / / returns null

There are special character classes that allow us to write complex regular expressions. There are many types of elements in RegEx, some of which are as follows:

Character regular:\ W-alphanumeric,\ d-numeric,\ D-no number

Character class regular: [xmury] xmury interval, [^ x] does not have x

Quantity regularity: + at least one,? No or more, * more

Boundary regular, ^ start, $end

Examples are as follows:

/ * Character class * / var re1 = / [AEIOU] /; re1.exec ("Oval"); / / returns ["O", index: 0, input: "Oval"] re1.exec ("2456"); / / null var re2 = / [1-9] /; re2.exec ('mp4'); / / returns ["4", index: 2, input: "mp4"] / * Characters * / var re4 = /\ d\ D\ wman; re4.exec (' 1232W2sdf') / returns ["2W2", index: 3, input: "1232W2sdf"] re4.exec ('W3q'); / / returns null / * Boundaries * / var re5 = / ^\ d\ D\ w re5.exec (' 2W34'); / / returns ["2W3", index: 0, input: "2W34"] re5.exec ('W34567'); / / returns null var re6 = / ^ [0-9] {5}-[0-9] {5}-[0-9] {5} $/ Re6.exec ('23451-45242-99078'); / / returns ["23451-45242-99078", index: 0, input: "23451-45242-99078"] re6.exec ('23451 Mustang Quantifiers * / var re7 = /\ d +\ Dracula); re7.exec (' 2abcd'); / / returns ["2abcd", index: 0, input: "2abcd"] re7.exec ('23'); / returns null re7.exec (' 2abcd3') / / returns null var re8 = / (. *?) /; re8.exec ('

Hello JS developer

'); / / returns ["

Hello JS developer

"," p "," Hello JS developer ", index: 0, input:"

Hello JS developer

"]

In addition to exec, there are other functions, namely match, search, and replace, that can use regular expressions to find a string in another string, but these functions are used on the string itself.

"2345-678r9" .match (/ [amurz Amurz] /); / / returns ["r", index: 8, input: "2345-678r9"] "2345-678r9" .replace (/ [amurz Amurz] /, "); / / returns 2345-6789

Regex is an important topic that developers should understand so that they can easily solve complex problems.

9) understand map, reduce, and filter

Functional programming is a hot topic of discussion today. Many programming languages include functional concepts in new versions, such as lambdas (for example: Java > 7). In JavaScript, support for functional programming structures has been around for a long time. We need to learn more about the three main functions. Mathematical functions accept some input and return output. Pure functions return the same output from a given input. The function we are talking about now also satisfies purity.

Map

The map function is available in the JavaScript array, and with this function, we can get a new array by applying a conversion function to each element in the array. The general syntax of map is:

Arr.map ((elem) {process (elem) return processedValue}) / / returns new array with each element processed

Suppose we enter some unwanted characters in our recently used serial key and need to remove them. Instead of deleting characters through iteration and lookup, you can use map to do the same and get the resulting array.

Var data = ["2345-34r", "2e345-211,543-67i4", "346,598"]; var re = / [amerz Amurz] /; var cleanedData = data.map ((elem) = > {return elem.replace (re, ")}); console.log (cleanedData); / [" 2345-34 "," 2345-211 "," 543-674 "," 346-598 "]

Map accepts a function as an argument, which accepts an argument from an array. We need to return a processed element and apply it to all elements in the array.

Reduce

The reduce function organizes a given list into a final result. Do the same by iterating through the array and save the intermediate result to a variable. Here is a more concise way to deal with it. The general syntax for reduce of js is as follows:

Arr.reduce ((accumulator, currentValue, currentIndex) = > {process (accumulator, currentValue) return intermediateValue/finalValue}, initialAccumulatorValue) / / returns reduced value

Accumulator stores intermediate and final values. CurrentIndex and currentValue are the index and value of elements in the array, respectively. InitialAccumulatorValue is the initial value of accumulator.

One practical application of reduce is to flatten an array and convert the internal array into a single array, as follows:

Var arr = [[1,2], [3,4], [5,6]]; var flattenedArray = [1,2,3,4,5,6]

We can do this through normal iterations, but with reduce, the code is more concise.

Var flattenedArray = arr.reduce ((accumulator, currentValue) = > {return accumulator.concat (currentValue);}, []); / / returns [1,2,3,4,5,6]

Filter

Filter is closer to map, manipulating each element of the array and returning another array (different from the value returned by reduce). The filtered array may be shorter than the original array, because the filter condition excludes some of the things we don't need.

The filter syntax is as follows:

Arr.filter ((elem) = > {return true/false})

Elem is an element in an array, and the filter element is saved / excluded by true/false. Suppose we filter out elements that start with t and end with r:

Var words = ["tiger", "toast", "boat", "tumor", "track", "bridge"] var newData = words.filter ((str) = > {return str.startsWith ('t') & & str.endsWith ('r');}) newData / / (2) ["tiger", "tumor"]

When someone asks about the functional programming aspects of JavaScript, these three functions should be handy. As you can see, the original array has not changed in all three cases, which proves the purity of these functions.

10) understand the error handling mode

This is the JavaScript that many developers care least about. I see very few developers talk about error handling, and a good development approach is always careful to wrap JS code around try/catch blocks.

In JavaScript, as long as we write code at will, we may fail, as shown in:

("button") .click (function () {$.ajax ({url: "user.json", success: function (result) {updateUI (result ["posts"]);});})

Here, we are caught in a trap where we say that result is always a JSON object. But sometimes the server crashes and null is returned instead of result. In this case, null ["posts"] will throw an error. The correct way to deal with this may be as follows:

("button") .click (function () {$.ajax ({url: "user.json", success: function (result) {try {updateUI (result ["posts"]);} catch (e) {/ / Custom functions logError (); flashInfoMessage ();});})

The logError function is used to report errors to the server. FlashInfoMessage displays user-friendly messages, such as "currently unavailable services" and so on.

'when you think something unexpected is going to happen, throw the error manually, 'says Nicholas. Distinguish between fatal and non-fatal errors. The above error is related to the downtime of the back-end server, which is fatal. There, the customer should be informed that the service has been interrupted for some reason.

In some cases, this may not be fatal, but notify the server. To create such code, first throw an error, catch the error event from the window level, and then call API to log the message to the server.

ReportErrorToServer = function (error) {$.ajax ({type: "POST", url: "http://api.xyz.com/report", data: error, success: function (result) {}})) } / / Window error event window.addEventListener ('error', function (e) {reportErrorToServer ({message: e.message})})} function mainLogic () {/ / Somewhere you feel like fishy throw new Error ("user feeds are having fewer fields than expected...");}

This code does three main things:

Listening for window level error

Call API whenever an error occurs

Record in the server

You can also use the new Boolean function (es5,es6) to monitor the validity of variables before the program and not null, undefined.

If (Boolean (someVariable)) {/ / use variable now} else {throw new Error ("Custom message")}

Always consider that error handling is yours, not the browser.

Other (promotion mechanism and event bubbling)

All of the above concepts are basic concepts that JavaScript developers need to know. There are some internal details to know, which will be very helpful to you. These are how the JavaScript engine works in browsers. What are promotion mechanisms and event bubbles?

Promotion mechanism

Variable promotion is a process of raising the scope of a declared variable to a global role during code execution, such as:

DoSomething (foo); / / used before var foo; / / declared later

When doing this in a scripting language such as Python, it throws an error because it needs to be defined before it can be used. Although JS is a scripting language, it has a promotion mechanism in which JavaScript VM does two things when running the program:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

First scan the program, collect all variables and function declarations, and allocate memory space for it

Execute the program by populating the assigned variables. If there is no allocation, populate the undefined.

In the code snippet above, console.log prints "undefined". This is because the variable foo is collected on the * pass. The JS virtual machine looks for any value defined for the variable foo. This promotion can cause many JavaScript to throw errors in some places and use undefined in other places.

Learn some examples to figure out the promotion.

Event bubbling

Now things are bubbling up! According to Arun P, senior software engineer:

"when an event occurs in an element within another element, event bubbling and capture are two ways of event propagation in HTML DOM API, and both elements have registered handlers for the event, and the event propagation pattern determines the order in which the element receives the event."

With bubbling, the event is first captured and processed by the innermost element, and then propagated to the external element. For capture, the process is the opposite. We usually use the addEventListener function to attach events to the handler.

AddEventListener ("click", handler, useCapture=false)

UseCapture is the keyword for the third parameter, which defaults to false. Therefore, the bubbling mode is that the event is passed up from the bottom. On the contrary, this is capture mode.

Bubbling mode:

Function handler () {/ / do something here} function divHandler () {} function ulHandler () {} document.getElementById ("foo") .addEventListener ("click", handler)

Click the li element, and the sequence of events:

Handler () = > ulHandler () = > divHandler ()

In the figure, the processor triggers outward in sequence. Similarly, the capture model attempts to trigger the event inward from the parent element to the clicked element. Now change this line in the code above.

Document.getElementById ("foo") .addEventListener ("click", handler, true)

Sequence of events:

DivHandler = > ulHandler () = > handler ()

You should correctly understand event bubbles (whether directed to parent or child nodes) to implement the user interface (UI) to avoid any unwanted behavior.

These are the basic concepts in JavaScript. As I mentioned initially, in addition to work experience and knowledge, you are prepared to have an assistant to pass the JavaScript interview. Always keep learning. Pay attention to the development of * (Chapter 6). In-depth understanding of all aspects of JavaScript, such as V6 engine, testing, etc. The interview is not successful without mastering the data structure and algorithm. Oleksii Trekhleb has planned a great git repo that includes all the interview preparation algorithms that use JS code.

The BUG that may exist after the code deployment cannot be known in real time. In order to solve these BUG, we spent a lot of time debugging log. By the way, we recommend a useful BUG monitoring tool, Fundebug.

The answer to the question about the perfect guide for Javascript interview is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report