Careeroza
Hoisting
What is Hoisting?
Example
Before running code, JavaScript registers all declarations of a scope. Function declarations can be called before they appear; var exists early but is undefined:
console.log(sayHi());
console.log(score);
function sayHi() { return "hi"; }
var score = 10;Output
hi undefined
The Temporal Dead Zone
Example (error)
let and const are hoisted too, but cannot be used before their declaration line (the TDZ):
console.log(total);
let total = 5;Output
Uncaught ReferenceError: Cannot access 'total' before initialization
Tip: Declare variables at the top of their scope and functions before use; hoisting then never surprises you.