DEV Community

Cover image for Hoisting in JavaScript
Md Pervez Hossain
Md Pervez Hossain

Posted on

Hoisting in JavaScript

πŸ‘‰ Hoisting in JavaScript

  • Hoisting is a JavaScript behavior where you can access variables, functions, and classes even before they are declared in the code, without encountering any errors.

πŸ‘‰ Variable Hoisting :

  • Variables declared using var are hoisted and initialized to undefined During The Memory Creation Phase.
  • When Variables declared with let and const are also hoisted, but they are not initialized In Global Scope Means Browser Window Object. let And const Variable Initialized undefined in script memory, leading to a "Temporal Dead Zone" .

πŸ‘‰ Temporal Dead Zone :

  • When you declare variables with let and const, they are subject to the Temporal Dead Zone (TDZ). During the Memory Creation Phase of the execution context, let and const variables are initialized in the script's memory location but are not assigned a value. The TDZ refers to the period between when the variable enters the scope and when it is actually declared and initialized. During this time, any attempt to access the variable will result in a "Reference Error "

πŸ‘‰ Function Hoisting:

  • Function declarations are hoisted entirely During the Memory creation Phase, That's why the function can be called before its declaration in the code.
  • Function expressions are Also hoisted but it is treated as Variables and initialized to "undefined" In the Memory Creation Phase. If You Call This Function Before initialized it throw type Error that is β€œthat Variable is not a Function β€œ

Image description

πŸ‘‰ Class Hoisting:

  • Class declarations are hoisted, but unlike functions, they are not initialized. This means you cannot instantiate a class before its declaration.

πŸ‘‰ Execution Context:

  • Hoisting occurs in the memory allocation phase of the execution context. This is why we can use variables and functions before they are explicitly declared in the code.

πŸ‘‰ Undefined vs. Not Defined:

  • undefined: A variable has been declared Memory Location Has been Allocates For Variables and but not yet assigned a value.
  • not defined: A variable has not been declared at all. Means No Memory Location Allocates For Variables

Top comments (2)

Collapse
 
hendrikras profile image
Hendrik Ras

Great cheat sheet for the topic of hoisting. Thanks!

Collapse
 
pervez profile image
Md Pervez Hossain

Thank you