What is Hoisting in JavaScript?

Hoisting in JavaScript is a behavior in which variable and function declarations are moved, or “hoisted”, to the top of their containing scope during the compilation phase—before the code is executed. This means that you can use variables and functions before they are formally declared in the code.

Variables and Hoisting

When using the var keyword, the variable declaration is hoisted to the top of its function or global scope, but not the assignment. For example:

console.log(a); // undefined
var a = 5;

Internally, JavaScript interprets it like this:

var a;
console.log(a); // undefined
a = 5;

However, variables declared with let and const are also hoisted but not initialized. Accessing them before declaration results in a ReferenceError due to the “temporal dead zone”—the time between the start of the block and the actual declaration.

console.log(b); // ReferenceError
let b = 10;

Functions and Hoisting

Function declarations are fully hoisted, meaning both their name and body are moved to the top of their scope. You can call the function before it appears in the code:

greet(); // "Hello"

function greet() {
  console.log("Hello");
}

However, function expressions, whether defined with var, let, or const, are not hoisted in the same way. If defined with var, the variable is hoisted but not the function assignment.

sayHi(); // TypeError

var sayHi = function() {
  console.log("Hi");
};

Conclusion

Hoisting can lead to confusing bugs if not properly understood. Best practices include declaring variables at the top of their scope and using let or const instead of var to avoid unexpected behaviors.