DEV Community

Cover image for HOISTING
Vinoth Kumar
Vinoth Kumar

Posted on

HOISTING

HOISTING IN JS: The behavior where JavaScript moves the declarations of variables, functions, and classes to the top of their scope during the compilation phase.

  • Hoisting applies to variable and function declarations.
  • Initializations are not hoisted, they are only declarations.
  • 'var' variables are hoisted with undefined, while 'let' and 'const' are hoisted but remain in the Temporal Dead Zone until initialized.

TYPES OF HOISTING:

  1. Variable Hoisting with var.
  2. Variable Hoisting with let and const.
  3. Function Declaration Hoisting.
  4. Function Expression Hoisting.
  5. Hoisting with let and const in Functions.
  6. Hoisting with Classes.
  7. Re-declaring Variables with var.
  8. Hoisted Functions with Parameters.
  9. Hoisting in Nested Functions.

VARIABLE HOISTING WITH VAR: Declaration is hoisted to the top, but its value is not assigned until the code execution reaches the variable’s initialization. This results in the variable being assigned undefined during the hoisting phase.

EXAMPLE:

console.log(i); //ERROR UNDEFINED
var i = 100;
Enter fullscreen mode Exit fullscreen mode

VARIABLE HOISTING WITH LET AND CONSTANT: let and const are also hoisted, but they remain in a Temporal Dead Zone (TDZ) from the start of the block until their declaration is encountered. Accessing them before their declaration will throw a ReferenceError.

EXAMPLE:

console.log(i); //REFERENCE ERROR
let i = 200;
Enter fullscreen mode Exit fullscreen mode

FUNCTION DECLARATION HOISTING: Hoisted with both their name and the function body. This means the function can be called before its definition in the code.

EXAMPLE:

greet(); 
function greet() {
    console.log("Hello, VINOTH!");
}
Enter fullscreen mode Exit fullscreen mode

FUNCTION EXPRESSION HOISTING: Expressions are treated like variable declarations. The variable itself is hoisted, but the function expression is not assigned until the line of execution. This means calling the function before its assignment will result in an error.

EXAMPLE:

hello(); // TYPERROR: hello is not a function
let hello = function() {
    console.log("Hi!");
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)