JavaScript Hoisting Explained: Why var is Hoisted but Not let or const

So… why does this code NOT throw an error? 🤔 The reason is HOISTING ! console.log(a); var a = 10; 👉 JavaScript moves variable and function declarations to the top of the code before execution. This is called Hoisting. When JavaScript sees the code, it actually understands it like this 👇 var a; console.log(a); a = 10; 🤯 What’s happening here? The variable a is declared first But its value (10) is assigned later So when console.log(a) runs, a exists but has no value yet That’s why the output is: 👉 undefined 👉 NOT an error ❌ ⚠️ Important thing to remember: var is hoisted and initialized with undefined let and const are hoisted too, but NOT initialized This happens because let and const stay in the Temporal Dead Zone until they are declared. 🚀 Why hoisting matters? ✅ Helps you avoid unexpected bugs ✅ Makes your code more predictable ✅ Frequently asked in JavaScript interviews Follow BhaviDigital for beginner-friendly frontend & backend content 🚀 #JavaScript #WebDevelopment #Frontend #LearnJavaScript #CodingJourney #BhaviDigital

  • So… why does this code NOT throw an error? 🤔

The reason is HOISTING !



console.log(a);

var a = 10;



👉 JavaScript moves variable and function declarations to the top of the code before execution.

This is called Hoisting.



When JavaScript sees the code, it actually understands it like this 👇



var a;

console.log(a);

a = 10;



🤯 What’s happening here?

The variable a is declared first

But its value (10) is assigned later

So when console.log(a) runs, a exists but has no value yet



That’s why the output is:

👉 undefined

👉 NOT an error ❌



⚠️ Important thing to remember:

var is hoisted and initialized with undefined

let and const are hoisted too, but NOT initialized



This happens because let and const stay in the Temporal Dead Zone until they are declared.



🚀 Why hoisting matters?

✅ Helps you avoid unexpected bugs

✅ Makes your code more predictable

✅ Frequently asked in JavaScript interviews



Follow BhaviDigital for beginner-friendly frontend & backend co

To view or add a comment, sign in

Explore content categories