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. πŸ‘‡

Video: What is Hoisting in JavaScript

πŸ” 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

Popular posts from this blog

πŸš€ “JavaScript Debounce Made Simple + Live Example!”