In simple terms, hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is actually executed.
This means that you can use a variable or call a function before it's declared in your code, and JavaScript will still work as if it had been declared at the top. However, only the declarations are hoisted, not the initializations or assignments.
However, hoisting can sometimes lead to confusion or bugs if developers are not careful. That's why it's important to understand how hoisting works and to use proper coding practices, such as declaring variables where they are needed and using let
and const
for block-scoped variables, to avoid potential issues.
debugger //adding debugger to debug
console.log(a); // a = undefined, but not give any error
var a = "ajay";
let & const don't but it is not truth it will give error but behind the scene on memory phase it will allocate the undefined but JavaScript move const & let to a different zone which is temporal zone.
Temporal Dead Zone (TDZ) :
Temporal Dead Zone (TDZ) ek phase hai JavaScript mein jahan pe ek variable declare ho chuka hota hai par usse access nahi kiya ja sakta. Is phase mein variable exist karta hai lekin uska access karne par ReferenceError aata hai. Yeh phase let
aur const
keywords se declare kiye gaye variables ke liye hota hai, jahan pe variable declaration aur initialization alag hoti hai.
debugger //adding debugger to debug
console.log(a); //ReferenceError: Cannot access 'a' before initialization
//but if we use debugger it wil show us the undefind but we nt ablt to acess
const a = "ajay";
refers to a specific phase during the variable declaration process in JavaScript where a variable exists but cannot be accessed. This concept is related to the behavior of variables declared using let
and const
keywords with block scope.
console.log(myVar); // Throws ReferenceError: Cannot access 'myVar' before initialization
let myVar = 10; // Variable declaration
In this example, even though myVar
is declared using let
, attempting to access it before its declaration results in a ReferenceError
because it is still in the TDZ.
The Temporal Dead Zone ensures that variables declared with let
or const
are not accessed before they are initialized, helping to catch potential errors caused by uninitialized variables.
First Memory Creation start & then Execution phase
Pehle, JavaScript engine memory allocate karta hai variables aur functions ke liye. Phir, code execution shuru hota hai, jismein variables ko values assign ki jaati hain aur functions ko call kiya jaata hai. Is process ko samajhna zaroori hai taki hum code ko sahi tarah se likh sakein aur potential errors ko avoid kar sakein.
so is vjh se hi hoisting hota h phle memory phase fir execution. now same with functions also