JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Hoisting


In JavaScript, hoisting is a behavior in which variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use variables and functions before they are explicitly declared in the code. Understanding hoisting is crucial for avoiding unexpected results, writing cleaner code, and debugging effectively.

In this tutorial, you will learn about JavaScript hoisting, how it works with variables and functions, practical examples, common mistakes, best practices, and real-world applications.

Why Hoisting Is Important

Hoisting is important because it:

  • Explains why certain code works even if variables or functions are declared later

  • Helps prevent reference errors in some cases

  • Clarifies the behavior of var, let, and const declarations

  • Allows function declarations to be used before they appear in the code

  • Helps developers understand execution context and memory allocation

Without a clear understanding of hoisting, developers may encounter confusing behavior in their programs, particularly with variable shadowing and function calls.

How Hoisting Works

During the compilation phase, JavaScript scans the code for variable and function declarations. It then moves these declarations to the top of their scope. Importantly:

  • Function declarations are hoisted completely, meaning both the function name and body are moved to the top.

  • Variables declared with var are hoisted but initialized with undefined.

  • Variables declared with let and const are hoisted but are in a temporal dead zone until their declaration is reached. Accessing them before declaration results in a ReferenceError.

Hoisting with Variables

Using var

console.log(name); // undefined
var name = "Aarushi";
console.log(name); // Aarushi

Explanation:

  1. During compilation, JavaScript hoists the var name declaration to the top.

  2. The variable is initially undefined.

  3. When the assignment name = "Aarushi" occurs, the value is updated.

Using let and const

console.log(age); // ReferenceError
let age = 25;

console.log(score); // ReferenceError
const score = 90;

Variables declared with let or const cannot be accessed before their declaration due to the temporal dead zone.

Hoisting with Functions

Function Declarations

Function declarations are fully hoisted, allowing you to call the function before it appears in the code.

greet();

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

Output:

Hello, Priya!

Function Expressions

Function expressions are treated like variables. If assigned to var, let, or const, only the variable is hoisted, not the function body.

sayHello(); // TypeError: sayHello is not a function
var sayHello = function() {
    console.log("Hi, Saanvi!");
};

With var, the variable sayHello is hoisted but initialized as undefined. Calling it before assignment results in a TypeError. With let or const, accessing it before declaration results in a ReferenceError.

Practical Examples

Example 1: Using var Before Declaration

console.log(course); // undefined
var course = "JavaScript";
console.log(course); // JavaScript

Example 2: Function Declaration Hoisting

calculate();

function calculate() {
    console.log("Calculation done!");
}

The function can be invoked before its declaration because the function declaration is hoisted entirely.

Example 3: Function Expression Hoisting

console.log(getScore); // undefined
var getScore = function() {
    console.log("Score calculated!");
};
getScore(); // Score calculated!

Example 4: Let and Const Temporal Dead Zone

console.log(player); // ReferenceError
let player = "Aarushi";

console.log(level); // ReferenceError
const level = 5;

Accessing these variables before declaration causes a runtime error.

Example 5: Nested Function Hoisting

function outer() {
    inner();
    function inner() {
        console.log("Inner function executed");
    }
}

outer(); // Inner function executed

Nested function declarations are hoisted within their parent function scope.

Common Mistakes

  • Expecting let and const variables to behave like var

  • Calling function expressions before assignment

  • Assuming hoisting affects only functions, not variables

  • Using variables before initialization, leading to undefined or errors

  • Confusing the temporal dead zone with undefined values

Best Practices

  • Always declare variables at the top of their scope to improve readability

  • Use let and const for block-scoped variables to avoid unintended hoisting issues

  • Declare functions before calling them if using function expressions

  • Keep nested functions simple and predictable

  • Understand hoisting behavior to prevent subtle bugs

Real-World Applications

  • Structuring code in a readable and predictable manner

  • Debugging reference errors and undefined variables

  • Writing modular code with proper variable and function placement

  • Ensuring asynchronous code works correctly when using function expressions

  • Avoiding global variable pollution and conflicts

Summary of JavaScript Hoisting

JavaScript hoisting is a mechanism where variable and function declarations are moved to the top of their containing scope. Function declarations are fully hoisted, while var variables are hoisted but initialized with undefined. Variables declared with let and const are hoisted but remain in a temporal dead zone until their declaration. Understanding hoisting helps developers write cleaner, bug-free code, avoid common pitfalls, and make better decisions regarding variable and function declarations.


Practice Questions

  1. Access a var variable before its declaration and log its value. Explain the output.

  2. Access a let variable before its declaration and observe the result. Explain why it differs from var.

  3. Call a function declared with a function declaration before its definition and log the output.

  4. Call a function assigned to a function expression using var before its assignment. Explain the error.

  5. Call a function assigned to a function expression using let before its assignment. Explain the result.

  6. Inside a function, access a var variable before declaration and observe the output.

  7. Inside a function, access a let or const variable before declaration and explain the Temporal Dead Zone.

  8. Demonstrate variable hoisting by declaring multiple var variables in different blocks and accessing them outside the blocks.

  9. Write a function that uses a var counter variable and a nested function. Access the counter before initialization and after increment.

  10. Compare hoisting behavior of var, let, and const by creating variables of each type in the global scope and trying to access them before declaration.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top