Hoisting in JavaScript
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of thier scope before code execution. However, hoisting does not mean that the declarations are physically moved to the top. Instead, JavaScript's execution context first scans the entire code for declarations and register them in the memory before executing the code.
This means we can reference a variable or function before it is declared in the code.
How Hoisting works in Variables
-
Varibale hoisting with
varvarare hoisted but are initialized asundefinedExample 1:
console.log(a); // undefined var a = 1; console.log(a); // 1Example 2:
var a; console.log(a); // undefined a = 1; console.log(a); // 1
-
Varibale hoisting with
letandconstVaribale declared with
letandconstare hoisted but are not initialized. They remain in a temporal dead zone (TDZ) from the start of the block until thier declaration is encountered. Accessing them before declaration results in aReferenceError.Example:
console.log(x); // ReferenceError: Cannot access 'x' before initialization let x = 10; console.log(y); // ReferenceError: Cannot access 'y' before initialization const y = 12;
How Hoisting works in functions
-
Function Declarations
JavaScript hoists the entire function declaration to the top, making it callable anywhere within its scope.
Example:
hello(); // Hello, World! function hello() { console.log("Hello, World!"); }
-
Function Expressions
Function expressions, including arrow functions, behave differently
Example:
hello(); // TypeError: hello is not a function var hello = function() { console.log("Hello, World!"); }In this example
hellois declared usingvar, which is hoisted and initialized withundefined. So, if we try to invokehellogives "TypeError".
Hoisting in Different Scopes
| Scope | var Hoisting | let and const Hoisting |
|---|---|---|
| Global | Hoisted, initialized as undefined | Hoisted, but in TDZ (ReferenceError) |
| Function | Hoisted, initialized as undefined | Hoisted, but in TDZ (ReferenceError) |
| Block | Hoisted, but ignores block scope | Hoisted, but in TDZ (ReferenceError) |