What Is Hoisting in JavaScript?

Understand JavaScript hoisting, how it works with variables and functions, and best practices to avoid bugs in modern web development.


Back to Home

Table of content

Introduction

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.

What is Hoisting?

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.

How Hoisting Works

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.

Hoisting with var Variables

console.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

Hoisting with 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;

Hoisting with Functions

Function Declarations

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

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!");
};

Best Practices to Avoid Hoisting Bugs

  • Always declare variables at the top of their scope.
  • Use let and const over var to avoid confusion.
  • Declare functions before you use them, especially for function expressions.
  • Enable strict mode ('use strict';) to catch common mistakes.

Real-World Example

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.

Conclusion

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.

ES6
Frontend
Functions
Hoisting
JavaScript
Variables
Web Development