Mind~G
Javascript

Hoisting

Introduction

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope before code execution.

We can only hoisted var not const and let but let and const are also hoisted but kept in a special place called temporal dead zone. That means you cannot use them before you write them. if you used it will give the error.

What Gets Hoisted

  1. Variable declarations
  2. Function declarations

Variable Declarations

Example

console.log(a);
var a = 5;

Output: Undefined

In behind scene it looks like this because of Hoisting

var a;
console.log(a);
a = 5;

means variable existed but not get their value.

Function Declarations

Functions are fully hoisted if you use function declaration. means if defined any function using function keyword then it will fully hoisted with their logic. not only declaration.

If we used to define function using arrow function then there declaration only hoisted not their logic and it will throw error.

Example with function keyword

greet();
 
function greet() {
  console.log("Hello");
}

Output: Hello

because it is fully hoisted with their declaration and logic.

Example with arrow function keyword

greet();
var greet = function() {
  console.log("Hello");
}

Output: This will give an error. Because only the variable name greet is hoisted not the function value.

So behind the scenes

var greet;
greet(); // not a function yet
greet = function() { console.log("Hello"); }

Important Notes

  • var declarations are hoisted and initialized with undefined
  • let and const declarations are hoisted but remain in the Temporal Dead Zone (TDZ) until the line where they are declared is executed
  • Function declarations are fully hoisted with their implementation
  • Function expressions (arrow functions, function assigned to variables) are treated as variables and only the declaration is hoisted
  • Always declare variables at the top of their scope to avoid confusion

On this page