JS Hoisting
What Is Hoisting?
Hoisting means JavaScript processes declarations before running the code. The behavior depends on the declaration type. Understanding hoisting matters because it explains why some code that looks like it should fail with a ReferenceError actually runs (just with unexpected values).
Example: What Is Hoisting?
console.log(typeof laterFunction); // "function" - hoisted
function laterFunction() {}
var Hoisting
A var declaration is hoisted and starts with the value undefined until its assignment runs. Because of this, reading a var-declared variable before its assignment line gives undefined rather than an error, which can mask bugs where you forgot to initialize it.
Example: var Hoisting
console.log(x); // undefined, not an error
var x = 5;
let and const
let and const are hoisted too, but they stay in the temporal dead zone until their declaration is reached. Accessing a let/const variable before its declaration line throws a ReferenceError rather than returning undefined, which is why this in-between state is called the temporal dead zone.
Example: let and const
try {
console.log(y); // ReferenceError: temporal dead zone
} catch (e) {
console.log(e.message);
}
let y = 5;
Function Hoisting
Function declarations can be called before their declaration. Function expressions do not work the same way. This means you can organize helper function declarations below where they're used for readability, while function expressions assigned to a variable follow normal variable hoisting rules instead.
Example: Function Hoisting
sayHi(); // works, function declarations are fully hoisted
function sayHi() {
console.log("Hi!");
}
// sayBye(); // TypeError, sayBye is undefined here
var sayBye = function () { console.log("Bye"); };
Best Practices
Declare variables before using them. This makes code easier to read and avoids confusing hoisting behavior. Modern linters flag use-before-declaration automatically, which is one more reason relying on hoisting rather than declaring variables up front is considered poor practice.
Example: Best Practices
// Best practice: declare before use
let total = 0;
total = total + 5;
console.log(total);
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: