⚡ What Is Hoisting in JavaScript?

⚡ What Is Hoisting in JavaScript?

Hoisting means that JavaScript moves variable and function declarations to the top of their scope (before code execution) — but not the initialization.

So JavaScript “knows” about your variables and functions before it runs your code, but values are not yet assigned.


๐Ÿง  Example 1 — Variable Hoisting (with var)

console.log(a); // ๐Ÿ‘‰ undefined
var a = 10;

๐Ÿ” Behind the Scenes

JavaScript internally does this:

var a;       // Declaration is hoisted
console.log(a);
a = 10;      // Initialization stays in place

✅ So it doesn’t throw an error — it just logs undefined.


๐Ÿšซ let and const Are Not Fully Hoisted

console.log(b); // ❌ ReferenceError: Cannot access 'b' before initialization
let b = 20;

✅ Explanation:

  • let and const are hoisted, but they are not initialized until the execution reaches that line.

  • The time between hoisting and initialization is called the Temporal Dead Zone (TDZ).


๐Ÿงฉ Example 2 — Function Hoisting

sayHello(); // ✅ Works fine

function sayHello() {
  console.log("Hello!");
}

✅ Output:

Hello!

Why?

Because function declarations are fully hoisted — both their name and definition.


⚠️ Example 3 — Function Expression (Not Hoisted)

sayHi(); // ❌ TypeError: sayHi is not a function

var sayHi = function() {
  console.log("Hi!");
};

What Happens:

var sayHi; // declaration hoisted
sayHi();   // sayHi is undefined here
sayHi = function() {...}

So it throws a TypeError, not a ReferenceError.


✅ Summary Table

Type Hoisted? Initialized? Usable Before Declaration? Notes
var ✅ Yes ❌ No ⚠️ Yes, but undefined Function-scoped
let ✅ Yes ❌ No ❌ No (TDZ error) Block-scoped
const ✅ Yes ❌ No ❌ No (TDZ error) Block-scoped
Function Declaration ✅ Yes ✅ Yes ✅ Yes Fully hoisted
Function Expression ✅ Yes (name only) ❌ No ❌ No Acts like var

๐Ÿ’ก In Short

๐Ÿงฉ Hoisting = JavaScript’s way of processing declarations before executing code.
It means “you can use a function or variable before it appears in the code,” depending on how it’s declared.


Would you like me to show a visual memory diagram of how the JavaScript engine treats variables during hoisting (execution context + TDZ)?

Comments

Popular posts from this blog

Your build is currently configured to use incompatible Java 21.0.3 and Gradle 8.2.1. Cannot sync the project.

Error in Android Migration Gradle 7.5 to 8.5 - java.lang.NullPointerException: Cannot invoke "String.length()" because "" is null

Setting Up Jenkins for Flutter App on macOS