Tricky Javascript Interview Questions Tricky Javascript Interview Questions

This post is a collection of tricky interview questions based on different concepts in JavaScript. The difficulty level of question will increase as you read forward down the line in this post.

Number operators. Guess the output?

console.log(   2 + "2" );  
console.log( "2" + "2" );

console.log(   2 - "2" );
console.log( "2" - "2" );
console.log( "A" - "A" );

Think for a while before looking at the output.

Output
22 22 0 0 NaN

Here is the explanation,

Javascript + operator behaves as,

  • number operator when both operands are number
  • concat operator if any one or both of the operands are string.

Javascript - operator always behaves as number operator. if any one or both of the operands are string, Javascript attempts to convert it to a number, if not able to convert then return NaN.

Relational Operators. Guess the output ?

console.log( 10 < 20 < 30 );
console.log( 30 > 20 > 10 );

Have you guessed true in both the cases ? No, its not correct.

Output
true false

The output is true and false. Here is the explanation,

In Javascript relational operators are evaluated from left to right, false equals 0, and true equals 1 for number comparisons.

So comparison evaluation is something like this,

10 < 20 < 30  =>  true < 30  =>  1 < 30  => true
30 > 20 > 10  =>  true > 10  =>  1 > 10  => false

Comparison Operators. Guess the output ?

console.log( null == 0 );
console.log( null > 0  );
console.log( null >= 0 );

You might have guessed false in all the three cases but its not correct.

Output
false false true

In Javascript, equality check == and comparisons > < >= <= behaves differently.

For equality comparison,

  • null and undefined are comparable.
  • 0, false and "" (empty string) are comparable.
  • null and 0 are not comparable so null == 0 returns false.

For number comparison,

  • if one operand is number, it attempts to convert other operand to number.
  • null becomes 0 and undefined becomes NaN for number comparison so null > 0 returns false whereas null >= 0 returns true.

forEach loop. Guess the output?

const elements = [1, 2, 3, 4, 5];

elements.forEach(element => {
  console.log(element);

  if(element == 2){
    return;
    //break;
    //continue;
  }
})

Have you guessed it will print 1 and 2 ? Let’s look at the output,

Output
1 2 3 4 5

Yes, its confusing in Javascript. The reason is that we are passing a callback function in forEach loop which will be executed for each element no matter if we return.

If you use break or continue instead of return, you get either one of the error since these are not applicable for a callback function:

Uncaught SyntaxError: Illegal break statement
Uncaught SyntaxError: Illegal continue statement

From Official MDN docs:
There is no way to stop or break a forEach loop other than throwing an exception. If you need such behavior, the forEach method is the wrong tool. Early termination may be accomplished with:

  • A simple for loop
  • A for...of / for...in loops

Variable hoisting. Guess the output?

var foo = 1;

function myFun(){
  console.log(foo);
  
  var foo = 2;
}

myFun();

Have you guessed foo = 1 or foo = 2?

It’s neither one of them. It will print undefined. Here is the explanation,

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

Let’s see how it is interpreted by the compiler in hoisting process,

var foo;
foo = 1;

function myFun(){
  
  var foo;          // var hoisted and initialized with undefined
  console.log(foo); // undefined
  
  foo = 2;
}

myFun();

Closure. Guess the output?

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

Have you guessed it will print 0, 1, 2 after every 1 second ? Let’s look at the output,

Output
3 3 3

Actually it will print 3, 3, 3 after every 1 second. This is because of JavaScript Closure. Here is the explanation,

closure

A JavaScript closure is when an inner function has access to its outer function’s scope. In the following line of code:

setTimeout(function() { console.log(i); }, i*1000);

variable i is used in an inner function whereas it is actually declared in outer for loop. Inner function will be able to access the value of i through Closure.

hoisting

In Javascript hoisting process, declaration of i will be moved to the top of their scope, since i is defined using var in for loop, declaration of i will be moved to global scope in hoisting process.

After three iteration of for loop, value of global scoped variable i will be 3. All three closures will refer to this same i variable from global scope.

let

if i were defined using let instead of var in for loop, output would have been different. Why?

let is block scoped as opposed to var which is function scoped. Since for loop is also a block, value of i in each iteration is block scoped within that iteration and each closure has its own copy of i variable. Let’s look at the code,

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

this keyword. Guess the output?

var a = new Person("a");
var b = Person 
var c = Person("c");

function Person(fname) {
    this.fname = fname;
}

console.log("1.", fname);   
console.log("2.", a.fname);    
console.log("3.", b.fname);    
console.log("4.", c.fname);

Think for a while before looking at the output.

Output
1. c 2. a 3. undefined Uncaught TypeError: Cannot read property 'fname' of undefined

Here is the explanation,

  1. fname will print c. When you execute Person("c") function, this refers to global object window and this.fname is assigned value as c.
  2. a.fname will print a. When you execute function using new keyword new Person("a"), this refers to newly created object.
  3. b.fname will print undefined since you are just assigning a function object and not executing it. Person object is not having property named as fname
  4. function Person("c") doesn’t return anything so c is undefined and c.fname will throw error

Also read this post to understand all about this keyword with examples