Variable hoisting is one of the most important JavaScript concepts. In most interviews, you will see output-based questions where variables are accessed before they are assigned a value. Start with the easy questions and then move to the tricky ones.
Question 1
console.log(a); var a = 10;
The declaration is hoisted, but the assignment stays in place.
Question 2
var a = 10;
function test() {
console.log(a);
var a = 20;
}
test();
The local variable is hoisted inside the function.
Question 3
var a = 5;
function test() {
console.log(a);
}
test();
No local variable exists, so JavaScript uses the global variable.
Question 4
console.log(a); var a;
Variables declared with var are initialized with undefined.
Question 5
var a = 10;
function test() {
console.log(a);
}
var a = 20;
test();
The function reads the current value when it executes.
Question 6
var a = 10;
function test() {
console.log(a);
a = 30;
}
test();
console.log(a);
The global variable is updated because no local variable exists.
Question 7
console.log(a);
if (true) {
var a = 100;
}
var is function scoped, not block scoped.
Question 8
var a = 1;
function test() {
console.log(a);
var a = 2;
console.log(a);
}
test();
The local variable is hoisted and starts with undefined.
Question 9
var a = 10;
function test() {
console.log(a);
}
function demo() {
var a = 20;
test();
}
demo();
JavaScript uses lexical scope.
Question 10
var a = 1;
function test() {
console.log(a);
var a = a + 1;
console.log(a);
}
test();
undefined + 1 produces NaN.
Question 11
var a = 5;
(function () {
console.log(a);
var a = 15;
})();
The IIFE creates its own scope.
Question 12
console.log(a); var a = 10; console.log(a);
The declaration is hoisted but the value assignment is not.
Question 13
var a = 50;
function test() {
console.log(a);
if (true) {
var a = 100;
}
}
test();
The local variable inside the function is hoisted.
Question 14
var x = 1;
function test() {
x = 10;
console.log(x);
var x;
}
test();
The local variable is hoisted before execution starts.
Question 15
var a = 10;
function test() {
console.log(a);
function a() {}
}
test();
Function declarations are hoisted before code execution.