Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top.
1. Function Hoisting
greet();
function greet() {
console.log("Hello Sajin");
}
Output:
Hello Sajin
This works because function declarations are hoisted.
2. var Hoisting
console.log(name);
var name = "Sajin";
Output:
undefined
JavaScript behaves roughly like:
var name;
console.log(name);
name = "Sajin";
The declaration is hoisted, but the value assignment is not.
3. let and const
let and const are also hoisted internally, but they cannot be accessed before their declaration.
console.log(name);
let name = "Sajin";
This gives:
ReferenceError
The same applies to const:
console.log(age);
const age = 25;
4. Why is Hoisting useful?
The most practical example is function declarations:
calculate();
function calculate() {
let a = 10;
let b = 20;
console.log(a + b);
}
Output:
30
It allows you to organize code so that the main logic appears before the detailed function implementations.
Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the creation phase, before code execution.
Top comments (0)