10 typical JavaScript face questions

Source: Internet
Author: User

Issue 1: scope (SCOPE)

Consider the following code:

(function () {   var5;}) (); Console.log (b);

The above code will print out 5 . The pitfall of this problem is that there are two assignments in the immediate execution function expression (iife), but the variables are a declared using keywords var . This means that it a is a local variable of the function. In contrast, it b is assigned to the global scope (that is, the global variable).

Another pitfall of this problem is that "strict mode" () is not used in the function ‘use strict‘; . If strict mode is turned on, then the code will error "uncaught referenceerror:b is not defined". Keep in mind that if this is the expected behavior, strict mode requires that you explicitly refer to the global scope. So, you need to write like this:

(function () {   'usestrict';    var 5 ;}) (); Console.log (b);

Issue 2: Create a native (native) method

Stringdefine a function on the object repeatify . This function takes an integer argument to clarify that the string needs to be repeated several times. This function requires the string to repeat the specified number of times. As an example:

Console.log ('hello'. Repeatify (3));

hellohellohello,one possible way to do this is to print out the following:

String.prototype.repeatify = String.prototype.repeatify | | function (times) {   var';     for (var0; i < times; i++) {      this;   }    return str;};

This question tests the developer's knowledge of the inheritance and prototype ( prototype ) attributes in JavaScript. This also verifies that the developer has the ability to extend the native data type functionality (although this should not be done). Another key point here is to see how you can avoid rewriting methods that might already be defined. This can be done by detecting whether a method already exists before defining its own method.

String.prototype.repeatify = String.prototype.repeatify | | function (times) {/** /

This technique is useful when you are extending a JavaScript method.

Issue 3: Variable elevation (hoisting)

What is the result of executing the following code? Why?

function Test () {   console.log (a);   Console.log (foo ());       var 1 ;   function foo () {      return2;   }} Test ();

The result of the execution of this code is undefined and 2 .

The reason for this result is that variables and functions are promoted (hoisted) to the top of the function body. Therefore, when a variable a is printed, it exists in the function body (because it is a already declared), but it is still undefined . In other words, the above code is equivalent to the following code:

function Test () {   var  A;   function foo () {      return2;   }   Console.log (a);   Console.log (foo ());    1 ;} Test ();

Question 4: How ' this ' works in JavaScript

What is the result of the following code? Please explain your answer.

varFullName ='John Doe';varobj ={fullname:'Colin Ihrig', prop: {fullname:'Aurelio De Rosa', Getfullname:function () {return  This. FullName; }}};console.log (Obj.prop.getFullname ());varTest =Obj.prop.getfullname;console.log (Test ());

This code prints the result: Aurelio De Rosa and John Doe . The reason for this is that the keyword in JavaScript this refers to the function context, depending on how the function is called, not how it is defined.

In the first console.log() , the getFullname() function is called as an obj.prop object. Therefore, the current context refers to the latter, and the function returns the properties of the object fullname . Conversely, when getFullname() assigned to a test variable, the current context is a global object window because it is test implicitly the property of the global object. Based on this, the function window returns fullname , in this case, the first line of code set.

Question 5:call () and apply ()

Fix the previous issue so that the last console.log() print outputAurelio De Rosa。

This problem can be coerced into the context by applying or using a call() apply() method. In the following code, I use call(), but apply() can produce the same result:

Console.log (Test.call (Obj.prop));

Issue 6: Closures (Closures)

Consider the following code:

var nodes = document.getElementsByTagName ('button');  for (var0; i < nodes.length; i++) {   nodes[i].addeventlistener ('click  ', function () {      console.log ('youclicked element #' + i);   });}

Excuse me, if the user clicks on the first and fourth buttons, what is the result of the console printing separately? Why?

The code is printed two times You clicked element #NODES_LENGTH , which NODES_LENGTH is the number of nodes in the nodes.

The reason is that after the for loop is complete, i the value of the variable equals the length of the node list. Also, because in the scope of the i code add handler, the variable belongs to the handler's closure. You will remember that the value of the variable in the closure is not static, so i the value is not the value when the handler is added (for the list, the first button is 0, the second button is 1, and so on). When the handler will be executed, the current value of the variable will be printed on the console i , equal to the length of the node list.

Issue 7: Closures (Closures)

Fix the problem, make the first button when the output 0, click the second button when the output 1, and so on.

There are a number of ways to solve this problem, the following are mainly used in two ways to solve the problem.

The first solution uses an immediate execution function expression (iife) and then creates a closure to get the desired value of I. The code to implement this method is as follows:

 var  nodes = document.getElementsByTagName (  " button   "  for  (var  i = 0 ; i < nodes.length; I++  " click  "  return   function () {Console.log ( 
       
         "
        you clicked Element #        " + i); }}) (i));   

The other solution does not use Iife, but instead moves the function outside the loop. This method is implemented by the following code:

function Handlerwrapper (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 8: Data type

Consider the following code:

Console.log (typeofnull);  Objectconsole.log (typeof  {}); //objectconsole.log (typeof  []); //objectconsole.log (typeof undefined); //undefined

Most developers think typeof [] they will return Array . If you want to test whether a variable is an array

var myArray = []; if (MyArray instanceof Array) {   // do something ...}

Issue 9: Event loops

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

function Printing () {   console.log (1);   SetTimeout (function () {Console.log (2);   SetTimeout (function () {Console.log (30);   Console.log (4);} printing ();

Output results: 1 4 3 2

Wondering why the output order is this way, you need to figure out setTimeout() what to do, 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, click, scroll, and so on), Ajax callbacks, and setTimeout() the callbacks provided to and are setInterval() all processed in turn by the event loop. Therefore, when the function is called, the setTimeout() 0 provided callback is queued even if the delay time is set to . 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 "1" because it is the first sentence of the function and does not use a 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 10: Algorithm

Writes a isPrime() function that returns when it is a prime number true , otherwise returns false .

I think this is one of the most common questions in the interview. However, although the problem often arises and is simple, the level of math and arithmetic in the interviewee can be well seen from the answers provided by the interviewee.

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 remember: Negative numbers are not prime numbers. Likewise, 1 and 0 are not, so first test these numbers. In addition, 2 is the only even number in a prime number. There is no need to validate 4,6,8 with a loop. Furthermore, if a number cannot be divisible by 2, it cannot be divisible by 4,6,8. Therefore, your loops must skip these numbers. If you test the input even, your algorithm will be twice times slower (you test double 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.

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:

function IsPrime (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 a error.      return false; }   if(Number <2) {      return false; }    if(Number = = =2) {      return true; } Else if(Number%2===0) {      return false; }   varSquareRoot =math.sqrt (number);  for(vari =3; I <= squareroot; i + =2) {      if(number% i = = = =0) {         return false; }   }   return true;}

10 typical JavaScript face questions

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.