Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Variable Hoisting in JavaScript
When you can use a JavaScript variable before it is declared, it is done using a technique called hoisting. The parser reads through the complete function before running it.
The behavior in which a variable appears to be used before it is declared is known as hoisting. JavaScript moves variable declarations to the top of their scope during compilation.
Example: var Hoisting
For example, the following code works due to hoisting:
points = 200; var points; console.log(points);
200
The above works the same as if you had written:
var points; points = 200; console.log(points);
200
How Hoisting Works
JavaScript hoists declarations but not initializations. The variable declaration is moved to the top, but the assignment stays in place:
console.log(x); // undefined (not an error) var x = 5; console.log(x); // 5
undefined 5
let and const vs var
Variables declared with let and const are hoisted but remain in a "temporal dead zone" until declared:
try {
console.log(y); // ReferenceError
let y = 10;
} catch (error) {
console.log("Error:", error.message);
}
Error: Cannot access 'y' before initialization
Function Hoisting
Function declarations are completely hoisted, including their body:
sayHello(); // Works due to hoisting
function sayHello() {
console.log("Hello!");
}
Hello!
Conclusion
Hoisting moves var declarations to the top of their scope, but let and const remain inaccessible until declared. Always declare variables before use for clearer code.
