Skip to the content.

Common Javascript Interview Questions and Examples

Table of Contents

This list contains a longer list of important JavaScript questions. Not all of them will be asked during Front End Engineer interviews but they provide a well-rounded review of JavaScript concepts ranging from beginner to advanced topics.

No. Questions Level
1 Question 1: Predict the Output Basic
2 Question 2: Private Counter Using Closures Basic

Question 1: Predict the Output

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

Answer:

The let declaration creates a new block-scoped variable for each iteration, so the output will be:

0, 1, 2, 3, 4

Question 2: Private Counter Using Closures

function privateCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count,
    getCount: () => count,
  };
}

const counter = privateCounter();
console.log(counter.increment()); // Output: 1
console.log(counter.decrement()); // Output: 0
console.log(counter.getCount()); // Output: 0

Answer:

The privateCounter function creates a closure with a private count variable, which is manipulated through the increment, decrement, and getCount methods.

Output:

1
0
0

Question 3: Identify and Fix Closure Issue

Problematic Code:

for (var i = 1; i <= 5; i++) {
  setTimeout(() => console.log(`n = ${i}`), 0);
}

Answer:

The var keyword does not create block-scoped variables. By the time the callback executes, i is already 6.

Fixed Code Using IIFE:

for (var i = 1; i <= 5; i++) {
  (function (n) {
    setTimeout(() => console.log(`n = ${n}`), 0);
  })(i);
}

Fixed Code Using let:

for (let i = 1; i <= 5; i++) {
  setTimeout(() => console.log(`n = ${i}`), 0);
}

Expected Output:

n = 1
n = 2
n = 3
n = 4
n = 5

Question 4: Implicit Type Coercion

What will the following code output, and why?

console.log([] + {}); // ?
console.log({} + []); // ?

Answer:


Question 5: NaN Comparison

Explain the output of this comparison:

console.log(NaN === NaN); // ?
console.log(Object.is(NaN, NaN)); // ?

Answer:


Question 6: Hoisting Oddities

What will the following code output, and why?

function foo() {
  console.log(a);
  var a = 10;
  console.log(a);
}
foo();

Answer:


Question 7: Function and Block Scope

What is the output of this code?

if (true) {
  function test() {
    console.log('Inside function');
  }
}

test();

Answer:


Question 8: typeof null

Why does typeof null return "object"?

console.log(typeof null); // ?

Answer:


Question 9: Array Holes

What will the following code output?

const arr = [1, , 3];
console.log(arr.length); // ?
console.log(arr[1]); // ?

Answer: