Course contentsShow
← JavaScript
Lesson 97 of 2,7233. Variables and ScopeFree lesson

Class Hoisting and the TDZ

Classes are hoisted like let/const, requiring declaration before instantiation to avoid TDZ errors.

Class Hoisting and the TDZ

What you'll learn: How JavaScript classes are hoisted and why you can't use them before their declaration.

The Core Idea

Classes in JavaScript behave like let and const when it comes to hoisting—not like var or function declarations. This means classes are hoisted (the engine knows they exist), but they remain in the Temporal Dead Zone (TDZ) until their declaration is reached. If you try to instantiate a class before its declaration, you'll get a ReferenceError.

Think of it like this: The JavaScript engine makes a reservation for the class name, but the actual "class definition" isn't available until you reach the line where it's declared. Trying to use it early is like trying to check into a hotel room before check-in time—the reservation exists, but you can't access the room yet.

How It Works

// ❌ This throws ReferenceError
const myDog = new Dog(); // Cannot access 'Dog' before initialization

class Dog {
  constructor(name) {
    this.name = name;
  }
}
// ✅ This works fine
class Cat {
  constructor(name) {
    this.name = name;
  }
}

const myCat = new Cat("Whiskers");

Unlike function declarations (which are fully hoisted), classes must be declared before you use them. This prevents confusing situations where you might instantiate a class before seeing what it does.

Why This Matters

This behavior encourages you to organize your code logically—define classes at the top of their scope before using them. It's consistent with how let and const work, making the language more predictable.

Key Takeaway: Classes are hoisted but stuck in the TDZ until their declaration line, so always declare classes before instantiating them to avoid ReferenceErrors.