Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase, before the code has been executed.
This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
Variables declared with var are hoisted to the top and initialized with undefined.
console.log(a);
var a = 10;
console.log(a);
Variables declared with let and const are also hoisted, but they are not
initialized. Accessing them before the declaration results in a ReferenceError.
This period between the start of the block and the declaration is known as the Temporal Dead Zone (TDZ).
try {
console.log(b); // ReferenceError
} catch(e) {
console.log(e.message);
}
let b = 20;
console.log(b);
Function Declarations are fully hoisted. You can call them before they are defined in the code.
hello();
function hello() {
console.log("Hello World! I am hoisted.");
}
Function Expressions (assigning a function to a variable) behave like variable hoisting. If you use
var, it's undefined. If you use const, it's in the TDZ.
try {
greet(); // TypeError: greet is not a function
} catch(e) {
console.log(e.message);
}
var greet = function() {
console.log("Hi");
};
| Declaration | Hoisted | Initialized Value | Access Before Declaration |
|---|---|---|---|
| var | Yes | undefined | Returns undefined |
| let / const | Yes | Uninitialized (TDZ) | Throws ReferenceError |
| Function Declaration | Yes | The Function Code | Works Perfectly |
| Function Expression (var) | Yes | undefined |
Throws TypeError |
let and const over var to avoid accidental hoisting bugs.
Test your understanding of JavaScript Hoisting.
var.document.write(score); statement.var score = 100;.sayHi().sayHi function after the function call to log "Hi!" to the console.let hoisting behavior.document.write(age); statement.let age = 25;.ReferenceError that is thrown.foo() at the top of your script.var foo and assign an anonymous function to it.TypeError occurs instead of a ReferenceError.{}.document.write(x); statement that would cause a ReferenceError.let x = 10;.x.