DEV Community

Cover image for Understanding Hoisting in JavaScript
Moinul Islam
Moinul Islam

Posted on

Understanding Hoisting in JavaScript

What is Hoisting?
Hoisting is JavaScript's default behavior of moving declarations (not initializations) to the top of their scope during the compile phase.

How Hoisting Works (Two Phases)?

1. Compile Phase
Before executing your code, JavaScript scans the entire scope and sets up memory for all declared variables and functions:

  • var

    • Declaration is hoisted and initialized as undefined
    • You can access it before the line, but the value will be undefined
  • let and const

    • Declaration is hoisted, but not initialized
    • They stay in a Temporal Dead Zone (TDZ) until their actual line
    • Accessing them before declaration throws a ReferenceError
  • Function Declarations

    • The entire function (name + body) is hoisted
    • You can safely call the function before its declaration

2. Execution Phase
Now JavaScript executes your code line-by-line:

  • var variables receive their assigned value
  • let / const are initialized at their declaration line
  • Using let / const before this point causes an error due to TDZ
  • Hoisted functions (declared with function) can be called anytime

TDZ (Temporal Dead Zone)
let and const are hoisted, so you can’t use them before the line they are declared or it gives an error.

console.log(a);        // undefined (var is hoisted)
console.log(b);        // ReferenceError (let is in TDZ)
console.log(greet());  // "Hello" (function is hoisted)

var a = 10;
let b = 20;

function greet() {
  return "Hello";
}

var sayHi = function () {
  return "Hi";
};

console.log(sayHi());  // "Hi" (works only after assignment)
sole.log("Bye!");
};
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.