Problem Statement
What will be the output? console.log(x); var x = 5;
Explanation
The output is undefined because of hoisting.
Hoisting means JavaScript moves variable declarations to the top of their scope before running code. But it only moves the declaration, not the assignment.
What JavaScript actually does:
It moves var x to the top and initializes it as undefined. Then when you log x, it prints undefined. After that, x gets assigned the value 5.
Think of it like reading a book:
Before you start reading, you flip through and see all chapter titles first. JavaScript does the same with declarations. It sees them all first, then starts executing code.
Only var behaves this way. Let and const will throw an error if accessed before declaration.
Code Solution
SolutionRead Only
// Example 1: var hoisting
console.log(name); // undefined (not error!)
var name = 'John';
console.log(name); // 'John'
// What JavaScript does internally:
var name; // Declaration hoisted
console.log(name); // undefined
name = 'John'; // Assignment stays in place
console.log(name); // 'John'
// Example 2: Multiple variables
console.log(a, b, c); // undefined undefined undefined
var a = 1;
var b = 2;
var c = 3;
// Example 3: In functions
function test() {
console.log(score); // undefined
var score = 100;
console.log(score); // 100
}