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


Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during compilation. This means you can use a variable or function before it has been declared in the code. Understanding hoisting is critical to avoid unexpected results and write predictable JavaScript code.

Hoisting affects var variables, let and const (differently), and functions.

Hoisting with var

Variables declared with var are hoisted to the top of their function or global scope. Only the declaration is hoisted, not the initialization.

console.log(a); // undefined (declaration hoisted, not value)
var a = 5;
console.log(a); // 5
  • The JavaScript engine interprets the code like this:

var a;
console.log(a); // undefined
a = 5;
console.log(a); // 5
  • Accessing a var variable before declaration does not throw an error, but its value is undefined.

Hoisting with let and const

Variables declared with let and const are hoisted to the top of their block, but they are not initialized. Accessing them before declaration results in a ReferenceError. This period is called the Temporal Dead Zone (TDZ).

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

// console.log(c); // ReferenceError
const c = 20;
  • The TDZ starts from the block's start and ends at the variable declaration.

  • let and const prevent using variables before they are declared, making code safer.

Hoisting with Functions

Function Declarations

Function declarations are fully hoisted, meaning you can call the function before its definition.

greet(); // Works: Hello World

function greet() {
  console.log("Hello World");
}
  • JavaScript moves the entire function body to the top of the scope during compilation.

Function Expressions

Function expressions assigned to a variable behave differently based on the variable type (var, let, const).

// Using var
// greetVar(); // TypeError: greetVar is not a function
var greetVar = function() {
  console.log("Hello from var");
};

// Using let
// greetLet(); // ReferenceError
let greetLet = function() {
  console.log("Hello from let");
};
  • Function expressions are not hoisted like declarations, only the variable declaration may be hoisted depending on var, let, or const.

Hoisting and Scope

Hoisting occurs within the scope of the variable or function.

function example() {
  console.log(x); // undefined (var hoisted)
  var x = 10;

  if (true) {
    var y = 20; // Function-scoped
    let z = 30; // Block-scoped
  }

  console.log(y); // 20
  // console.log(z); // ReferenceError
}

example();
  • var is function-scoped; let and const are block-scoped.

  • Hoisting works within the respective scope.

Practical Examples

Example 1: Variable Hoisting

console.log(name); // undefined
var name = "Alice";
console.log(name); // Alice
  • Declaration is hoisted, but value assignment stays in place.

Example 2: Function Hoisting

sayHello(); // Works

function sayHello() {
  console.log("Hello!");
}
  • Function declaration is hoisted entirely, so it can be called before definition.

Example 3: Function Expression Hoisting

// greet(); // TypeError: greet is not a function
var greet = function() {
  console.log("Hi");
};
greet(); // Works after assignment
  • Only the variable greet is hoisted, not the function itself.

Hoisting and Closures

Hoisting affects closures by determining when variables are initialized and available.

function counter() {
  console.log(count); // undefined
  var count = 0;

  return function() {
    count++;
    console.log(count);
  };
}

const myCounter = counter();
myCounter(); // 1
myCounter(); // 2
  • var count is hoisted within counter(), so the inner function can access it.

Best Practices

  1. Use let and const instead of var to avoid confusing hoisting issues.

  2. Declare variables at the top of their scope to improve readability.

  3. Be cautious with function expressions; function declarations are safer if hoisting is desired.

  4. Understand temporal dead zone to avoid reference errors with let and const.

  5. Avoid relying on hoisting for production-level code; explicit order improves maintainability.

Summary of the Tutorial

  • Hoisting moves variable and function declarations to the top of their scope during compilation.

  • var is hoisted and initialized with undefined.

  • let and const are hoisted but not initialized, resulting in a temporal dead zone.

  • Function declarations are fully hoisted; function expressions are not hoisted like declarations.

  • Understanding hoisting helps avoid unexpected undefined values and reference errors.

  • Best practice: use let/const and declare variables/functions at the top of their scope for clarity.

Mastering hoisting is essential to write predictable, bug-free JavaScript code, especially in larger applications with nested functions and complex scopes.


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.


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