Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope before the code runs.
This means you can use functions and variables before declaring them, though the behavior is slightly different for each.
🧾 Example with Function:
sayHello(); // ✅ Works due to hoisting
function sayHello() {
console.log("Hello!");
}
✅ Function declarations are fully hoisted, so they can be called even before they appear in the code.
🧾 Example with Variable:
console.log(a); // ❌ undefined (not an error)
var a = 5;
Behind the scenes, JavaScript does this:
var a; // declaration hoisted
console.log(a);
a = 5; // assignment stays in place
✅ Variable declarations are hoisted, but initializations are not.
🧠 Important Points:
varis hoisted and initialized withundefined.letandconstare hoisted but not initialized, leading to a Temporal Dead Zone if accessed before declaration.- Function declarations are hoisted fully.
In short: Hoisting lets you use declarations before their actual code position, but how it works depends on whether it’s a variable or a function.