JavaScript Runtime

Hoisting

Understand how JavaScript prepares variables and functions before your code starts executing.

Learn what actually happens during JavaScript's Memory Creation Phase, why var behaves differently from let and const, how function declarations are hoisted, and how to avoid common interview mistakes.

Estimated Time

13 minutes

Difficulty

Beginner

Progress

0% Complete

What is Hoisting?

Imagine JavaScript reads your entire file before running it. During this first pass, it reserves memory for variables and functions. That preparation process is called Hoisting.

The important part: JavaScript prepares declarations first, but it still executes your code line by line. Assignments do not jump to the top.

What Hoisting is

Memory Creation Phase

Execution Phase

Variable Hoisting

Function Hoisting

Temporal Dead Zone

var vs let vs const

Function Declaration vs Function Expression

Common Interview Questions

JavaScript Execution Flow

How JavaScript Runs Your File

Hoisting makes more sense when you separate setup from execution.

1

Source Code

JavaScript receives the file exactly as you wrote it.

2

Memory Creation Phase

JavaScript reserves names for variables and functions before running code.

3

Execution Phase

JavaScript runs line by line and updates values.

4

Output

Console logs, returned values, and errors appear from executed lines.

Interactive Visualizer

Watch var Hoisting Happen

Step through source code, memory, call stack, console output, and execution notes.

Source Code
1console.log(a);
2
3var a = 10;
4
5console.log(a);
Memory
a
undefined
Call Stack
Global Execution Context
Console
(empty)
Execution
Memory Creation

Before any line runs, JavaScript sees var a and stores a with the value undefined.

Hoisting Comparison

var vs let vs const

All three declarations are prepared, but they are not prepared in the same way.

var

Memory

undefined

Access

Can access before declaration

Output

undefined

let

Memory

Memory reserved

Access

Cannot access before declaration

Output

ReferenceError

const

Memory

Memory reserved

Access

Cannot access before declaration

Output

ReferenceError

Temporal Dead Zone

The Unsafe Zone Before let and const

The variable name exists, but JavaScript blocks access until the declaration executes.

1console.log(userName);
2
3let userName = "Zubair";
4
5console.log(userName);

Current phase

Temporal Dead Zone

Access here throws ReferenceError because userName is still inside the Temporal Dead Zone.

ReferenceError
Function Hoisting

Declarations Work Early. Expressions Do Not.

The word function is not enough. The declaration style decides what JavaScript stores in memory.

1sayHello();
2
3function sayHello() {
4 console.log("Hello");
5}

Memory

sayHello: Function()

Output

Hello

Function declarations are stored in memory as complete functions during the memory creation phase.

Function Declaration

Hoisted

Works before declaration

Function Expression

Not callable before initialization

Acts like the variable used to store it

Arrow Function

Behaves like let or const

Cannot run before initialization

Class Declaration

Temporal Dead Zone

Name exists, but cannot be used early

Memory Visualization

Memory Before Execution

This is the mental picture to keep during interviews.

a

undefined

var declaration

b

TDZ

let declaration

c

TDZ

const declaration

sayHello()

Function()

function declaration

Code Playground

Run Hoisting Examples

Switch between examples, step through execution, and inspect memory and console output.

1console.log(score);
2var score = 42;
3console.log(score);
Console

Click Run to see output.

Memory
score: undefined
score: 42

var is hoisted and initialized with undefined, then updated when the assignment runs.

Common Mistakes

Hoisting Traps to Avoid

Most hoisting bugs come from mixing up prepared memory with real assigned values.

Using let before declaration and expecting undefined.

Using const before declaration and expecting undefined.

Thinking variables physically move to the top of the file.

Confusing undefined with ReferenceError.

Calling function expressions before initialization.

Real World Examples

Where Hoisting Shows Up

Hoisting is not just an interview topic. It affects startup order, modules, utilities, and React files.

Configuration Variables

Declare config before use so startup code never depends on accidental hoisting behavior.

Environment Variables

Read environment values into const variables before passing them into services.

Initialization

Initialize application state before functions begin consuming it.

Module Imports

Imports are prepared before module code runs, which is why they appear available at the top level.

React Components

Function declarations make reusable components and helpers easier to call from nearby code.

Utility Functions

Function declarations are useful when you want helpers to be readable below the main flow.

React

Function Components

React components are often function declarations because they are named, reusable, and easy to read in stack traces.

React

Hooks Order

Hooks cannot be called conditionally because React depends on the same call order during every render.

React

Imports

Import declarations are processed before module execution, so imported values are available throughout the module.

Common Interview Questions

Hoisting Interview Prep

Each answer includes a simple explanation, detailed explanation, interview answer, example, memory trick, and common mistake.

Simple explanation

Hoisting is JavaScript preparing variable and function names before code starts running.

Detailed explanation

During memory creation, JavaScript scans the code and creates memory slots for declarations. var starts as undefined, function declarations become full functions, and let, const, and class declarations stay unavailable until initialized.

Interview answer

Hoisting is JavaScript's creation-phase behavior where declarations are registered before execution. The behavior differs for var, let, const, functions, and classes.

Real example

console.log(a); var a = 10; logs undefined first.

Memory trick

JavaScript prepares names first, then runs lines.

Common mistake

Saying declarations physically move to the top.

Interactive Quiz

Check Your Hoisting Model

Fifteen interview-style questions with explanations and why each wrong option fails.

Progress

0/15 answered

Score: 0/15

1. What is hoisting in JavaScript?

2. What does this output first: console.log(a); var a = 10;

3. Why does let throw a ReferenceError before declaration?

4. Which declaration is initialized with undefined during memory creation?

5. Which can usually be called before it appears in the file?

6. What is the Temporal Dead Zone?

7. What is undefined?

8. What happens when you call a const arrow function before initialization?

9. What happens during execution phase?

10. Which statement about hoisting is most accurate?

11. How do class declarations behave before initialization?

12. Which is a best practice?

13. Why do imports feel hoisted?

14. What should you prefer for a variable that never changes?

15. What is the main interview trap about hoisting?

Visual Cheatsheet

Hoisting Summary

A final comparison table for quick revision before interviews.

Feature
var
let
const
Hoisted
Yes
Yes
Yes
Initialization
undefined
Uninitialized
Uninitialized
TDZ
No
Yes
Yes
Can Access Before Declaration
Yes
No
No
Can Reassign
Yes
Yes
No
Can Redeclare
Yes in same scope
No
No
Scope
Function
Block
Block

Always declare variables before using them.

Prefer const by default.

Use let only when reassignment is required.

Avoid var in modern JavaScript.

Prefer function declarations for reusable utilities that benefit from being callable early.

Copy-ready Code Examples

Production-Friendly Hoisting Patterns

Use clear declaration order and deliberate function styles in real projects.

Safe Configuration
1const apiBaseUrl = process.env.NEXT_PUBLIC_API_URL;
2
3function createApiUrl(path: string) {
4 return `${apiBaseUrl}${path}`;
5}

Configuration is declared before helpers use it, so readers do not need to reason about hoisting.

Reusable Utility Declaration
1const total = calculateCartTotal(items);
2
3function calculateCartTotal(items) {
4 return items.reduce((sum, item) => {
5 return sum + item.price * item.quantity;
6 }, 0);
7}

A function declaration can be called before it appears, which can keep the high-level flow readable.

Avoid TDZ Bugs
1const featureFlags = loadFeatureFlags();
2
3if (featureFlags.enableCheckout) {
4 initializeCheckout();
5}

Declare and initialize values before branching on them.

Modern Function Expression
1const formatPrice = (amount) => {
2 return new Intl.NumberFormat("en-US", {
3 style: "currency",
4 currency: "USD",
5 }).format(amount);
6};
7
8console.log(formatPrice(49));

Function expressions and arrow functions are excellent after initialization.