What is hoisting
Watch the walkthrough
Open on InstagramRevision clarifications
Hoisting describes declaration setup, not literal movement of source lines. The temporal dead zone starts on entering the scope and ends at initialization. Function expressions follow the rules of their variable binding.
The source notes below are copied unchanged apart from line endings. Examples are independent; some deliberately throw or depend on browser markup.
Original HackTheCode notes
Hoisting is a mechanism in JavaScript that moves all variable and function declarations to the top of their scope before code execution. This means that a variable or function can be used before it has been declared.
- var: only declaration hoisted
- let and const: Declarations hoisted but not initialized, leading to a temporal dead zone (this is the period between variable declaration and the initialization).
- Functions: Function declarations are fully hoisted, except functions initializations.
console.log(dog); // undefined
var dog = "πΆ"; // var
console.log(dog); // "πΆ"
console.log(rabbit); // ReferenceError: Cannot access 'rabbit' before initialization
let rabbit = "π"; // let
console.log(rabbit); // "π"
console.log(her); // ReferenceError: Cannot access 'her' before initialization
const her = "π"; // const
console.log(her); // "π"
console.log(foo()); // "Hello, world!"
function foo() {
return "Hello, world!";
}
console.log(car()); // TypeError: car is not a function
var car = function () {
return "π Starting!";
};
console.log(car()); // "π Starting!"