What is hoisting in JavaScript?

Learn how JavaScript moves variable and function declarations to the top of their scope.

beginnerFundamentalsjavascripthoistingscope
Published: 11/3/2025
Updated: 11/3/2025

Question

What is hoisting in JavaScript?


Answer

Hoisting is JavaScript’s default behavior of moving variable and function declarations to the top of their scope during the compilation phase.

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

Here, the declaration var a is hoisted, but its assignment (a = 5) is not.

Functions are hoisted completely:

sayHello();
function sayHello() {
  console.log('Hello!');
}

This works because function declarations are hoisted with their definitions.

Real-World Example

Be careful when using var before initialization—it can lead to undefined values. With let and const, hoisting still occurs, but accessing them before declaration throws a ReferenceError.

Quick Practice

Predict the output:

console.log(msg);
let msg = 'Hello, World!';

Summary

Hoisting makes declarations available before they appear in code — understand it to avoid the “undefined” trap.

Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions

Does let or const get hoisted?

Yes, but they remain uninitialized until declared — this is called the temporal dead zone.


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.