Js Hoisting in JavaScript
? JavaScript Hoisting
Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope (script or function).
? What Gets Hoisted?
| Type | Hoisted | Initialized |
|---|---|---|
var | ? Yes | ? No |
let / const | ? Yes | ? No (Temporal Dead Zone) |
function (declaration) | ? Yes | ? Yes |
function (expression) | ? Yes | ? No |
? Example: var Hoisting
console.log(x); // undefinedvar x = 5;? Behind the scenes:
var x;console.log(x); // undefinedx = 5;? let and const are Hoisted But Not Initialized
console.log(y); // ? ReferenceErrorlet y = 10;This is due to the Temporal Dead Zone — the time between hoisting and initialization.
? Function Declarations Are Fully Hoisted
sayHello(); // ? Worksfunction sayHello() { console.log("Hello!");}? Function Expressions Are Not Fully Hoisted
sayHi(); // ? TypeError: sayHi is not a functionvar sayHi = function () { console.log("Hi!");};Only the variable (sayHi) is hoisted, not the function assignment.
? Summary
Declarations (
var,let,const,function) are hoisted.Only
functiondeclarations are fully initialized when hoisted.letandconstare in a Temporal Dead Zone until initialized.
Want visual diagrams or hoisting in loops/scope?