Coders Read

7 JavaScript Interview Question

In this article, We’ll cover some common concepts based questions of one the most interesting programming language called JavaScript. There are many simple questions which look tricky in JavaScript. A clear understanding with concepts may help us to fill the gap and overcome those tricky questions.

After attending and conducting couple of interviews for the role of frontend developers, I have come up with this article. Hope this helps you before you’re ready for the interviews…

Understanding with concept of Closure, Timeouts and Scoping.

Closure in simple terms, this means that variables and properties inside a function are exclusive to that function, but the function can have access to outer properties.

This sounds simple, But the problem comes when your interviewer asks you a question some what similar to the code below.

for (var i = 0;  i < 5;  i++) {
    setTimeout(function log(){
        console.log(i);
    }, 1000);
}

No, output of the above code is not 0,1,2,3,4

When we run this, all of them are 5. And the reason is because, console.log(i) executes immediately and reference whatever the value of (i) is . Runs immediately at console.log itself. However, after one second, this entire loop has already gone through every iteration and the variable (i) here is being overwritten with every iterations.

Here, the setTimeout function creates a function (closure) which has the access to its outer scope, which is the loop that contains the index (i). After the iterations, the function is executed and it prints out the value of (i), which at the end of the loop is at 5.The problem here is that by the time the first setTimeout() runs, (i) is already at 5, and there is no way to reference it.

Solution : Two simple ways to fix this issue are-

a. By creating an Immediately Invoked Function Expression:

for (var i = 0; i < 5; i++) {
   setTimeout((function(param){
        console.log(i);
    })(i), 1000);
}

b. By using ES6 feature Let, which provides you a block scope.

for (let i = 0;  i < 5;  i++) {
    setTimeout(function log() {
        console.log(i);
    }, 1000);
}

The above solutions works perfect, i.e you get the output as 0,1,2,3,4.

Additional: Here the output are displayed all at once. What if the you are asked to get each number in output to be displayed after an interval of one second.

Well here is the solution. The second parameter of setTimeout needs to be multiplied by (i).

for (let i = 0;  i < 5;  i++) {
    setTimeout(function log() {
        console.log(i);
    }, i*1000);
}

Understanding on sort method working with array of numbers.

Sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Say, if there is an array of number which needs to be sorted. What should the below code return as output.

var myArray = [45,10,21,54,1,55,100];
myArray.sort();

If your guess is that this will output as [1, 10, 21, 45, 54, 55, 100], Then you are not correct. Sorting numbers is unfortunately not that simple. If we apply the sort method directly to a numbers array, we will see an unexpected result.

By default, the sort method sorts elements alphabetically. Above way to sort an array of number won’t sort the array properly.

Solution: Sort numerically adding a new method to handles numeric sorts.

a. Output for below ascending sort : [1, 10, 21, 45, 54, 55, 100]

myArray.sort((a, b) => a - b);

b. Output for below ascending sort : [100, 55, 54, 45, 21, 10, 1]

myArray.sort((a, b) => b - a);

Write a function to check if given parameter is even or odd without using any conditional statement

This is a logical question to check on your way of approach to a given problem.

Worried how to perform the check without using if else or ternary. Well the solution is funny and weird enough to make you think for few mins during the interview.

Solution: Well the solution to this is use of array or objects.

function checkNumber(num){
    const check = ['even', 'odd'];
    console.log(`${num} is ${check[num%2]}`);
}checkNumber(6); // 6 is even
checkNumber(5); // 5 is odd

Slice is an in-built method which can be used to trick you in the interview.

We all know that Slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end. The original array will not be modified.

But what happens if we use slice while to extract array values before we push a new value to the array.

Given below code is a code snippet executes which may not give you the desired output.

var obj = {
    name : 'Sourabh',
    sports : ['Chess', 'Football', 'Snooker']
}var mySports= obj.sports.slice();
obj.sports.push('Bowling');
console.log(mySports);

If your guess is to have output as [“Chess”, “Football”, “Snooker”, “Bowling”] then you are not correct. But if your guess is [“Bowling”] then yes, you are wrong again.

Solution: The output is [“Chess”, “Football”, “Snooker”].

Reason is that even though array is a reference type, still we are using slice method which creates a new reference pointer for the array.

Identify global and local variable.

Local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them.

Global variables are variables that are defined outside of functions. These variables have global scope, so they can be used by any function without passing them to the function as parameters.

Here is the code where global and local variable needs to be identified.

function myFunc() {
    let x = y = 0;
    return x += 1;
}myFunc();
console.log(typeof x);
console.log(typeof y);

Solution: Here ‘x’ is a local variable where as ‘y’ id a global variable.

Hence, typeof x is ‘undefined’. The variable x exists within myFunc() scope and not available in the outside scope. Where as y is a global variable with the value 0, the typeof y is ‘number’.

You can understand the above code like the one given below.

function myFunc() {
    let x;
    window.y = 0;
    x= window.y;
    return x+= 1;
}myFunc();
typeof x;
typeof window.y;

Loosing of ‘this’.

‘this’ keyword refers to an object, that object which is executing the current bit of javascript code. In other words, every javascript function while executing has a reference to its current execution context called ‘this’.

Here is the code which uses ‘this’ to refer the values within the same scope and it is expected to display the greetings message.

let greeting = {
    message: 'Good morning!', 
    name: 'Sourabh',displayMessage() {
        console.log(`Hello ${this.name}, ${this.message}`);
    }
};setTimeout(greeting.displayMessage, 1000);;

Unfortunately, it gives the output as Hello undefined, undefined.

Here setTimeout() function uses the greeting.displayMessage as a callback, still it invokes greeting.displayMessage as a regular function, rather than a method. And during a regular function invocation this equals the global object, which is window in the case of the browser environment.

Solution: We can either make use of wrapper function or can use built-in method bind.

a. Using wrapper function.

This will work because it receives greeting from the outer lexical environment, and then calls the method normally.

let greeting = {
    message: 'Good morning!', 
    name: 'Sourabh',displayMessage() {
        console.log(`Hello ${this.name}, ${this.message}`);
    }
};setTimeout(function() {
  greeting.displayMessage();
}, 1000);

b. Bind keyword can be used.

Here we take the method greeting.displayMessage and bind it to greeting. The displayMessage is a “bound” function, that can be called alone or passed to setTimeout (doesn’t matter, the context will be right).

let greeting = {
    message: 'Good morning!', 
    name: 'Sourabh',displayMessage() {
        console.log(`Hello ${this.name}, ${this.message}`);
    }
};let welcomeMessage = greeting.displayMessage.bind(greeting);setTimeout(welcomeMessage, 1000);

Singleton Pattern In JavaScript

In JavaScript context, Singleton is an object that is used to create namespace and group together a related set of methods and attributes (encapsulation) and if we allow to initiate then it can be initiated only once.

The simplest way I can think of, to create a singleton pattern which consumes less time and also avoids the amount of cross question in the interview is here.

function getInstance() {
  if(typeof instance === 'object') {
   console.log("object exists");
    return instance;
  }
  instance = this
}var a = new getInstance();
var b = new getInstance(); // object exists
var c = new getInstance(); // object exists

If you didn’t know any of these, you likely have grown at least a little in your knowledge of JavaScript. And if you knew them all, then hopefully this was an attempt to practice and grow your knowledge.

. . . . .

Good luck on your interviews. Enjoy reading… Thanks!

Sourabh Sinha

Add comment

Follow us

Feel free to get in touch. I love meeting interesting people and making new friends.

Any suggestions will be appreciated.