23. What is Hoisting?

S
Soumya Jana
Sun Mar 09 2025

What is Hoisting in JavaScript?

Hoisting is a JavaScript mechanism where variables and function declarations are moved (hoisted) to the top of their scope before the code execution. This means that you can use variables and functions before declaring them in your code.

However, only declarations are hoisted, not initializations.


Hoisting with var

js
console.log(x); // Output: undefined var x = 5; console.log(x); // Output: 5

Explanation:

  • The declaration var x; is hoisted to the top, but the assignment x = 5; is not.
  • So, console.log(x); before initialization prints undefined.

Hoisting with let and const

js
console.log(y); // ReferenceError: Cannot access 'y' before initialization let y = 10;

Explanation:

  • Unlike var, let and const are hoisted but remain in a "temporal dead zone" (TDZ) until their declaration is encountered.
  • This means you cannot access y before it's declared.

Hoisting with Functions

Function Declarations

js
greet(); // Output: Hello, World! function greet() { console.log("Hello, World!"); }

Explanation:

  • Function declarations are fully hoisted, meaning you can call them before they are defined.

Function Expressions (Not Hoisted)

js
greet(); // TypeError: greet is not a function var greet = function() { console.log("Hello, World!"); };

Explanation:

  • Here, greet is hoisted as undefined, so calling it before initialization causes an error.

Summary

TypeHoisted?Usable Before Declaration?
var✅ Yes⚠️ Yes, but undefined
let✅ Yes❌ No (TDZ Error)
const✅ Yes❌ No (TDZ Error)
Function Declaration✅ Yes✅ Yes
Function Expression (var)✅ Yes❌ No (undefined)

Would you like more examples or a deep dive into TDZ? 🚀

Related Posts:

View All Related Posts
Sign In To Write A Comment
Copyright © 2025 codewithjana.com