[Turn] 5 JavaScript face questions

Source: Internet
Author: User


Issue 1: Closures


Consider the following code:


varnodes = document.getElementsByTagName(‘button‘);for(vari = 0; i < nodes.length; i++) {   nodes[i].addEventListener(‘click‘,function() {      console.log(‘You clicked element #‘+ i);   });}


Excuse me, what will the console output if the user clicks the first and fourth buttons? Why?



Answer



The purpose of the above code is to detect an important concept of javascript: closures. For every JavaScript developer, if you want to write more than 5 lines of code in a Web page, it's important to understand and use closures accurately. If you want to start learning or just want to brush up on closures, I highly recommend that you read this tutorial: Colin Ihrig writes JavaScript Closures demystified.



Okay, back to the code above. The console outputs two times you clicked Element #NODES_LENGTH, where #nodes_length equals the number of elements in the NODES. When the For loop ends, the value of the variable i is equal to the length of the nodes. In addition, because I is the function scope when the event is added, the variable i belongs to the closure of the event. Since the value of the variable in the closure is not static, the value of I is not the value given when the event is added (for example, I is 0 when the first button is added, and I is 1 when the second button). When the event is executed, the console outputs the current value of the variable i, i.e. I equals the length of the nodes.


Issue 2: Closures


Fix the problem, make the first button when the Output 1, click the second button when the output 2.


Answer


There are a number of ways to solve this problem, and I'll give you two of them below.



The first solution is to use a iife to create another closure to get the desired I value. The corresponding code is as follows:


varnodes = document.getElementsByTagName(‘button‘);for(vari = 0; i < nodes.length; i++) {   nodes[i].addEventListener(‘click‘, (function(i) {      returnfunction() {         console.log(‘You clicked element #‘+ i);      }   })(i));}


Instead of using Iife, the other solution moves the function out of the loop, with the following code:


functionhandlerWrapper(i) {   returnfunction() {      console.log(‘You clicked element #‘+ i);   }}varnodes = document.getElementsByTagName(‘button‘);for(vari = 0; i < nodes.length; i++) {   nodes[i].addEventListener(‘click‘, handlerWrapper(i));}
Issue 3: Data type


Consider the following code:


console.log(typeofnull);console.log(typeof{});console.log(typeof[]);console.log(typeofundefined);
Answer


This problem may seem a bit silly, but it tests the knowledge of the TypeOf operator. Many JavaScript developers are unaware of the uniqueness of TypeOf. In this example, the console outputs the following:


objectobjectobjectundefined


The most surprising output could be the third, and many developers think TypeOf [] will return an array. If you want to test whether a variable value is an array, you can write the following code:


varmyArray = [];if(myArrayinstanceofArray) {   // do something...}
Issue 4: Event loops


What is the result of running the following code? Please explain.



functionprinting() {   console.log(1);   setTimeout(function() { console.log(2); }, 1000);   setTimeout(function() { console.log(3); }, 0);   console.log(4);}printing();

Answer


Output Result:


1432


To figure out why numbers are output in this order, you need to figure out what settimeout () is doing and how the browser's event loop works. The browser has an event loop that is used to check the event queue and handle deferred events. UI events (for example, clicks, scrolling, etc.), Ajax callbacks, and callbacks provided to settimeout () and setinterval () are processed sequentially by the event loop. Therefore, when the settimeout () function is called, the provided callback is queued even if the delay time is set to 0. The callback stays in the queue until the specified time runs out, and the engine starts to perform the action (if it is not currently performing other actions). Therefore, even if the settimeout () callback is delayed by 0 milliseconds, it will still be queued and will not execute until the other non-deferred statements in the function have been executed.



With these realizations, it is easy to understand that the output is "4" because it is the first sentence of the function and does not use the settimeout () function to delay it. Then output "4" because it is not delayed by the number and is not queued. Then, the remaining "2", "3", both are queued, but the former needs to wait a second, the latter waiting for 0 seconds (which means that the engine completes the first two outputs immediately after the completion of the). This explains why "3" precedes "2".


Issue 5: Algorithm


Write a IsPrime () function that determines the prime number and returns True if it is a prime number, otherwise false.


Answer


I think this is one of the most frequently asked questions in the interview. Although the problem is recurring and simple, the candidate's mathematical and algorithmic abilities are well seen in the answers provided by the candidate.



First, because JavaScript differs from C or Java, you cannot trust the type of data that is passed. If the interviewer does not explicitly tell you, you should ask him if he needs to do an input check, or if he does not check the direct write function. Strictly speaking, the input of the function should be checked.



2nd to remember, negative numbers are not prime numbers. Similarly, 1 and 0 are not, therefore, to test these numbers. In addition, 2 is the only number that is both even and prime. There is no need to validate 4,6,8 with a loop. Furthermore, if a number cannot be divisible by 2, it cannot be evenly divisible by 4,6,8, so your loop needs to skip these numbers. There are some other more sensible optimizations that I'm using for most of the situation. For example, if a number cannot be divisible by 5, it is not divisible by multiples of 5. Therefore, there is no need to detect 10,15,20 and so on. If you have a deeper understanding of the solution to this problem, I suggest you go to the relevant Wikipedia introduction.



Finally, you don't need to check the numbers that are larger than the root of the input numbers. I feel that people will miss out on this and will not get negative feedback for that. However, showing this aspect of knowledge will give you extra points.



Now that you have the background of this problem, here are the solutions to summarize all of the above considerations:


functionisPrime(number) {   // If your browser doesn‘t support the method Number.isInteger of ECMAScript 6,   // you can implement your own pretty easily   if(typeofnumber !== ‘number‘ || !Number.isInteger(number)) {      // Alternatively you can throw an error.      returnfalse;   }   if(number < 2) {      returnfalse;   }   if(number === 2) {      returntrue;   }elseif(number % 2 === 0) {      returnfalse;   }   varsquareRoot = Math.sqrt(number);   for(vari = 3; i <= squareRoot; i += 2) {      if(number % i === 0) {         returnfalse;      }   }   returntrue;}
Conclusion


This article discusses several other important JavaScript concepts in the form of questions and exercises that are important to the front-end developer interview. I hope you will be able to answer these questions smoothly, or learn something new from here so that you can have a better performance in your next interview.



[Turn] 5 JavaScript face questions


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.