DEV Community

Dev Cookies
Dev Cookies

Posted on

đź”® What is Hoisting?

Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope (script or function) before the code is executed.

đź§  Think of it as:

“JavaScript scans your code for variable and function declarations before running it, and moves those declarations to the top.”


đź§Ş Example 1: Variable Hoisting

console.log(x); // undefined
var x = 10;
Enter fullscreen mode Exit fullscreen mode

You’d think it would throw an error, but nope — output is undefined because:

var x;        // declaration is hoisted
console.log(x); // undefined
x = 10;       // assignment stays in place
Enter fullscreen mode Exit fullscreen mode

âť— var vs let / const

console.log(y); // ❌ ReferenceError
let y = 5;
Enter fullscreen mode Exit fullscreen mode

With let and const, declarations are hoisted, but not initialized. They stay in a Temporal Dead Zone (TDZ) until the line where they’re declared.


⚙️ Example 2: Function Hoisting

greet(); // âś… Works!
function greet() {
  console.log('Hello!');
}
Enter fullscreen mode Exit fullscreen mode

👉 Entire function declarations are hoisted (both name and body).

BUT…

sayHi(); // ❌ TypeError: sayHi is not a function
var sayHi = function() {
  console.log('Hi!');
};
Enter fullscreen mode Exit fullscreen mode

Because here, only the variable sayHi is hoisted (with undefined), not the function.


📝 Summary

Feature Hoisted? Initialized? Accessible Before Declaration?
var âś… Yes âś… Yes (with undefined) âś… Yes (but undefined)
let / const ✅ Yes ❌ No ❌ No (TDZ error)
Function Declaration âś… Fully âś… Yes âś… Yes
Function Expression (var) ✅ var only ❌ No ❌ No (TypeError)

\

Top comments (0)