5 Typical JavaScript Interview Exercises

Aurelio De Rosa
Aurelio De Rosa
Share
JavaScript developers are in high demand in the IT world. If this is the role that best expresses your knowledge, you have a lot of opportunities to change the company you work for and increase your salary. But before you are hired by a company, you have to demonstrate your skills in order to pass the interview process. In this article, I’ll show you five typical questions asked for a frontend job to test the JavaScript skills of the candidate and their relative solutions. It’ll be fun!

Question 1: Scope

Consider the following code:
(function() {
   var a = b = 5;
})();

console.log(b);
What will be printed on the console?

Answer

The code above prints 5. The trick of this question is that in the IIFE there are two assignments but the variable a
is declared using the keyword var. What this means is that a is a local variable of the function. On the contrary, b is assigned to the global scope. The other trick of this question is that it doesn’t use strict mode ('use strict';
) inside the function. If strict mode was enabled, the code would raise the error Uncaught ReferenceError: b is not defined. Remember that strict mode requires you to explicitly reference to the global scope if this was the intended behavior. So, you should write:
(function() {
   'use strict';
   var a = window.b = 5;
})();

console.log(b);

Question 2: Create “native” methods

Define a repeatify
function on the String object. The function accepts an integer that specifies how many times the string has to be repeated. The function returns the string repeated the number of times specified. For example:
console.log('hello'.repeatify(3));
Should print hellohellohello.

Answer

A possible implementation is shown below:
String.prototype.repeatify = String.prototype.repeatify || function(times) {
   var str = '';

   for (var i = 0; i < times; i++) {
      str += this;
   }

   return str;
};
The question tests the knowledge of the developer about inheritance in JavaScript and the prototype property. It also verifies that the developer is able to extend native data type functionalities (although this should not be done). Another important point here is to demonstrate that you are aware about how to not override possible already defined functions. This is done by testing that the function didn’t exist before defining your own:
String.prototype.repeatify = String.prototype.repeatify || function(times) {/* code here */};
This technique is particularly useful when you are asked to shim a JavaScript function.

Question 3: Hoisting

What’s the result of executing this code and why.
function test() {
   console.log(a);
   console.log(foo());
   
   var a = 1;
   function foo() {
      return 2;
   }
}

test();

Answer

The result of this code is undefined and 2. The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don’t retain any assigned value. So, at the time the variable a is printed, it exists in the function (it’s declared) but it’s still undefined
. Stated in other words, the code above is equivalent to the following:
function test() {
   var a;
   function foo() {
      return 2;
   }

   console.log(a);
   console.log(foo());
   
   a = 1;
}

test();

Question 4: How this works in JavaScript

What is the result of the following code? 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

The code prints Aurelio De Rosa
and John Doe. The reason is that the context of a function, what is referred with the this keyword, in JavaScript depends on how a function is invoked, not how it’s defined. In the first console.log() call, getFullname() is invoked as a function of the obj.prop
object. So, the context refers to the latter and the function returns the fullname property of this object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test
is implicitly set as a property of the global object. For this reason, the function returns the value of a property called fullname of window, which in this case is the one the code set in the first line of the snippet.

Question 5: call() and apply()

Fix the previous question’s issue so that the last console.log() prints Aurelio De Rosa
.

Answer

The issue can be fixed by forcing the context of the function using either the call() or the apply() function. If you don’t know them and their difference, I suggest you to read the article What’s the difference between function.call and function.apply?. In the code below I’ll use call()
but in this case apply() would produce the same result:
console.log(test.call(obj.prop));

Conclusion

In this article we’ve discussed five typical questions that are asked at interviews to test a JavaScript developer. The actual questions may differ from interview to interview but the concepts and the topics covered are usually pretty similar. I hope you had fun testing your knowledge. In case you didn’t know some of all of the answers, don’t worry: there is nothing that studying and experience can’t fix. If you have been asked some other interesting questions at interviews, don’t hesitate to share them with us. It’ll help a lot of developers.

Frequently Asked Questions (FAQs) about JavaScript Interview Exercises

What are some common mistakes to avoid during JavaScript coding interviews?

One of the most common mistakes is not understanding the problem fully before starting to code. Take your time to understand the problem, ask clarifying questions if needed. Another mistake is not considering edge cases. Always think about potential edge cases and how your code would handle them. Also, avoid hard-coding values. Your solution should work for all inputs, not just the provided examples. Lastly, remember to communicate your thought process. Interviewers are interested in how you approach problems, not just the final solution.

How can I prepare for JavaScript coding interviews?

Start by understanding the basics of JavaScript thoroughly. This includes understanding concepts like closures, promises, async/await, and ES6 features. Practice coding problems on platforms like LeetCode, HackerRank, and Codewars. Also, read up on common JavaScript interview questions and try to solve them on your own. Lastly, understand how JavaScript works under the hood. This includes understanding the event loop, call stack, and JavaScript’s non-blocking nature.

What are closures in JavaScript and why are they important?

Closures in JavaScript are functions that have access to the parent scope, even after the parent function has closed. They are important because they enable data privacy and are used in function factories and module patterns. Understanding closures is crucial as they are a fundamental part of JavaScript.

Can you explain the concept of ‘this’ in JavaScript?

This’ in JavaScript is a special keyword that refers to the context in which a function is called. It’s value is determined by how a function is called. It can refer to the global object, the object that’s currently being processed by the function, the object that was created by a constructor function, or the object specified when using call, apply, or bind methods.

How does JavaScript handle asynchronous operations?

JavaScript handles asynchronous operations using callbacks, promises, and async/await. Callbacks are functions that are passed as arguments to other functions and are invoked after some operation has been completed. Promises are objects that represent the eventual completion or failure of an asynchronous operation. Async/await is a syntactic sugar over promises that makes asynchronous code look and behave like synchronous code.

What are prototypes in JavaScript?

Prototypes in JavaScript are the mechanism by which JavaScript objects inherit features from one another. JavaScript is often described as a prototype-based language, and understanding prototypes is key to understanding JavaScript.

Can you explain the difference between ‘==’ and ‘===’ in JavaScript?

==’ is the loose equality operator and it converts the operands to the same type before making the comparison. On the other hand, ‘===’ is the strict equality operator and it does not do type conversion, it compares the operands as they are.

What is the event loop in JavaScript?

The event loop is a mechanism in JavaScript that constantly checks the call stack to see if it’s empty. If it is, it takes the first task from the task queue and pushes it to the call stack. It’s what allows JavaScript to be non-blocking and handle asynchronous operations.

What are JavaScript promises?

Promises in JavaScript are objects that represent the eventual completion or failure of an asynchronous operation. They can be in one of three states: pending, fulfilled, or rejected. Promises are used to handle asynchronous operations in a more flexible way than callbacks.

What are some common JavaScript design patterns?

Some common JavaScript design patterns include the module pattern, the prototype pattern, the observer pattern, and the singleton pattern. Understanding these patterns can help you write more efficient, maintainable, and scalable code.