What is Hoisting in JavaScript? 🔄 Explained with Example
📌 What is Hoisting in JavaScript?
In this post, we’ll understand one of the most commonly asked JavaScript interview questions: What is Hoisting? I’ve also added a video below that explains hoisting visually. 👇
🔍 What is Hoisting?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
🧠 Think of it like this:
Even if you declare your variables or functions at the bottom of the file, JavaScript will act as if they were declared at the top — but only the declarations, not initializations.
📂 Example 1: Variable Hoisting
console.log(x); // undefined
var x = 10;
🔎 Explanation: The declaration var x is hoisted to the top, but the assignment = 10 is not. So x exists but is undefined at the time of the console.log.
⚠️ Let’s Try with let or const
console.log(y); // ReferenceError
let y = 20;
Note: Variables declared with let and const are also hoisted but are not initialized. They remain in a temporal dead zone until the declaration is encountered.
📘 Function Hoisting
greet(); // "Hello!"
function greet() {
console.log("Hello!");
}
✅ Function declarations are fully hoisted. So you can call the function before it's defined.
📺 Watch the Video
For a complete breakdown with visuals and explanations, watch the full video above or on YouTube.
🔗 Useful Links
Thanks for reading! If you found this helpful, don’t forget to leave a comment and share this post with fellow developers. 🚀
Comments
Post a Comment