About Lesson
What is Hoisting?
Hoisting is a JavaScript mechanism where variable and function declarations are moved (or “hoisted”) to the top of their containing scope during the compile phase, making them accessible before their actual declaration in the code. However, only declarations are hoisted, not initializations.
Types of Hoisting:
1. Variable Hoisting:
- var: Hoisted and initialized to undefined. Accessing it before initialization will not throw an error but result in undefined.
- let and const: Hoisted but remain in the Temporal Dead Zone until the declaration is executed. Accessing them before initialization results in a ReferenceError.
JavaScript
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
console.log(y); // ReferenceError
let y = 10;
2. Function Hoisting:
Functions declared using the function keyword are fully hoisted and can be called before their definition.
JavaScript
greet(); // Output: Hello, World!
function greet() {
console.log("Hello, World!");
}
- Function Expressions: Not hoisted because they are assigned to variables, and the variable itself follows the hoisting rules.
- Arrow Functions: Also not hoisted as they are function expressions.
Real-Life Use Case:
Hoisting allows you to organize your code logically, placing helper functions and declarations anywhere in the code, improving readability.
JavaScript
calculateArea(5, 10); // Works due to function hoisting
function calculateArea(width, height) {
console.log(`Area: ${width * height}`);
}