10 typical JavaScript interview questions

  • 2021-08-05 08:35:46
  • OfStack

Question 1: Scope (Scope)

Consider the following code:


(function() {
 var a = b = 5;
})();
console.log(b);

What will the console (console) print out?

Answer: 5

If strict mode is turned on, the code will report an error of "Uncaught ReferenceError: b is not defined". Remember, if this is the expected behavior, strict mode requires you to explicitly refer to the global scope. So, you need to write something like this:


(function() {
 'use strict';
 var a = window.b = 5;
})();
console.log(b);

Problem 2: Create a "native (native)" method

Defines an repeatify function on an String object. This function takes an integer argument to specify how many times the string needs to be repeated. This function requires the string to repeat the specified number of times. For example:

console.log('hello'.repeatify(3));

hellohellohello should be printed.

Answer:


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

Here, another key point is to see how you can avoid overriding methods that may have been defined. This can be done by detecting whether the method already exists before defining your own method.

String.prototype.repeatify = String.prototype.repeatify || function(times) {/* code here */};

Question 3: Variable promotion (Hoisting)

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


function test() {
 console.log(a);
 console.log(foo());
 var a = 1;
 function foo() {
  return 2;
 }
}
test();

Answer:

The execution results of this code are undefined and 2.

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


function test() {
 var a;
 function foo() {
  return 2;
 }
 console.log(a);
 console.log(foo());
 a = 1;
} 
test();

Question 4: How does ` this ` work in javascript

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


var fullname = 'John Doe';
var obj = {
 fullname: 'Colin Ihrig',
 prop: {
  fullname: 'Aurelio De Rosa',
  getFullname: function() {
   return this.fullname;
  }
 }
};
console.log(obj.prop.getFullname());
var test = obj.prop.getFullname;
console.log(test());

Answer:

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

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

Question 5: call () and apply ()

Fix the first problem and have the last console. log () print out Aurelio De Rosa.

Answer:

This problem can be solved by using the call () or apply () methods to cast the context.

console.log(test.call(obj.prop));

Problem 6: Closures (Closures)

Consider the following code:


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

Excuse me, if the user clicks the first and fourth buttons, what are the results printed by the console respectively? Why?

Answer:

Both prints are values of nodes. length.

Problem 7: Closures (Closures)

Fix the problem above, so that when you click the first button, you will output 0, when you click the second button, you will output 1, and so on.

Answer:

There are many ways to solve this problem, and the following two methods are mainly used to solve this problem.

The first solution uses the immediate execution function expression (IIFE) to create another 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++) {
 nodes[i].addEventListener('click', (function(i) {
  return function() {
   console.log('You clicked element #' + i);
  }
 })(i));
}

Another solution does not use IIFE, but moves the function outside of the loop. This method is implemented by the following code:


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

Question 8: Data types

Consider the following code:


console.log(typeof null);
console.log(typeof {});
console.log(typeof []);
console.log(typeof undefined);

Answer:


(function() {
 'use strict';
 var a = window.b = 5;
})();
console.log(b);
0

Question 9: Event loop

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


(function() {
 'use strict';
 var a = window.b = 5;
})();
console.log(b);
1

Answer:


(function() {
 'use strict';
 var a = window.b = 5;
})();
console.log(b);
2

To understand why the output sequence is this way, you need to understand what setTimeout () does and how the browser's event loop works. The browser has 1 event loop to check the event queue and handle delayed events. UI events (for example, clicks, scrolls, etc.), Ajax callbacks, and callbacks provided to setTimeout () and setInterval () are handled in turn by event loops. Therefore, when the setTimeout () function is called, the supplied 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 begins to perform an action (if it does not perform any other action at present). Therefore, even if the setTimeout () callback is delayed by 0 milliseconds, it will still be queued and will not be executed until the other non-delayed statements in the function have been executed.

Question 10: Algorithms

Write an isPrime () function that returns true if it is prime, or false if not.

Answer:

I think this is one of the most common questions in interviews. However, although this question often occurs and is simple, the answers provided by the interviewee provide a good indication of the interviewee's mathematical and algorithmic level.

First of all, because JavaScript is different from C or Java, you can't trust the data type passed. If the interviewer doesn't explicitly tell you, you should ask him if he needs to do input checking, or write the function without checking. Strictly speaking, the input of the function should be checked.

The second point to remember is that negative numbers are not prime numbers. Similarly, 1 and 0 are not, so test these numbers first. In addition, 2 is the even number of prime numbers with only 1. There is no need to use a loop to verify 4, 6, 8. Furthermore, if a number cannot be divisible by 2, then it cannot be divisible by 4, 6, 8, etc. Therefore, your loop must skip these numbers. If you test even numbers, your algorithm will be 2 times slower (you test double numbers). There are 1 more sensible optimization options available, and the one I use here is for most situations. For example, if a number cannot be divisible by 5, it will not be divisible by a multiple of 5. Therefore, there is no need to detect 10, 15, 20, etc.

At the last point, you don't need to check a number larger than the square of the entered number. I feel that people will miss this point, and they will not get negative feedback because of it. However, showing this knowledge will give you extra points.

Now that you have the background knowledge of this problem, here is a solution that summarizes all 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 (typeof number !== 'number' || !Number.isInteger(number)) {
  // Alternatively you can throw an error.
  return false;
 }
 if (number < 2) {
  return false;
 }
 if (number === 2) {
  return true;
 } else if (number % 2 === 0) {
  return false;
 }
 var squareRoot = Math.sqrt(number);
 for(var i = 3; i <= squareRoot; i += 2) {
  if (number % i === 0) {
   return false;
  }
 }
 return true;
}

Related articles: