Understand JavaScript hoisting, how it works with variables and functions, and best practices to avoid bugs in modern web development.
Table of content
Hoisting is a fundamental JavaScript behavior that often confuses both beginners and experienced developers. Understanding hoisting can help you write cleaner, more predictable code and prevent subtle bugs in your web development projects.
Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope (global or function) before code execution. This affects both var
variable declarations and function declarations.
When you run JavaScript code, the JavaScript engine first scans for variable and function declarations. It “hoists” these declarations to the top of their scope, so you can use them before they appear in the code. However, only the declarations are hoisted – not the initializations for variables.
var
Variablesconsole.log(a); // undefined
var a = 10;
console.log(a); // 10
a
is hoisted, but not its assignment. The engine treats the code as:
var a;
console.log(a); // undefined
a = 10;
console.log(a); // 10
let
and const
let
and const
are also technically hoisted, but they are not initialized until the code reaches their declaration. Accessing them before their declaration results in a ReferenceError, due to the Temporal Dead Zone (TDZ).
console.log(b); // ReferenceError
let b = 5;
Function declarations are fully hoisted. You can call them before you declare them in your code.
sayHello(); // "Hello, world!"
function sayHello() {
console.log("Hello, world!");
}
Function expressions assigned to variables (var
, let
, const
) are not hoisted in the same way. Only the variable declaration is hoisted, not the assignment:
greet(); // TypeError: greet is not a function
var greet = function() {
console.log("Hi!");
};
let
and const
over var
to avoid confusion.strict mode
('use strict';
) to catch common mistakes.function calculate() {
console.log(total); // undefined
var total = 10 + 5;
}
calculate();
This logs undefined
instead of throwing an error, showing how var
hoisting can produce unexpected results.
JavaScript hoisting can be puzzling, but knowing how it works is essential for robust web development. Prefer let
and const
for clearer, safer code, and always declare variables and functions near the top of their scope.