JS Interview Questions
Top JavaScript Questions

Top JavaScript Interview Questions

This are the output based questions that are frequently asked in JavaScript interviews.

Scope of Variables in JavaScript

What will be the output of the following code?

Question 1

Click to see the code
output-based-questions.js
{
  let a = 1;
  let b = 2;
 
  console.log(a);
  console.log(b);
}
console.log(a);
console.log(b);

Output:

Click to see the output

The following output will be displayed:

1
2
ReferenceError: a is not defined

Question 2

Click to see the code
output-based-questions.js
{
  const a = 1;
  const b = 2;
 
  console.log(a);
  console.log(b);
}
console.log(a);
console.log(b);

Output:

Click to see the output

The following output will be displayed:

1
2
ReferenceError: a is not defined

Question 3

Click to see the code
output-based-questions.js
{
  var a = 1;
  var b = 2;
 
  console.log(a);
  console.log(b);
}
console.log(a);
console.log(b);

Output:

Click to see the output

The following output will be displayed:

1
2
1
2
💡

let and const are block-scoped variables, so they are not accessible outside the block.


Hoisting

What will be the output of the following code?

Question 1

Click to see the code
output-based-questions.js
{
  console.log(a);
  var a = 1;
}

Output:

Click to see the output

The following output will be displayed:

undefined

The variable a is hoisted to the top of the function, so it is accessible before it is declared.

Question 2

Click to see the code
output-based-questions.js
{
  console.log(a);
  let a = 1;
}

Output:

Click to see the output

The following output will be displayed:

ReferenceError: Cannot access 'a' before initialization
💡

let and const are not hoisted to the top of the function, so they are not accessible before they are declared.

Question 3

Click to see the code
hoisting.js
function foo() {
  console.log(a);
  var a = 1;
}
 
foo();

Output:

Click to see the output

The following output will be displayed:

undefined

Question 4

Click to see the code
hoisting.js
fucntion fooo() {
    x = 10;
    console.log(x);
}

Output:

Click to see the output

The following output will be displayed:

10
💡

But there is one problem in this: Always use use strict to avoid such errors.