Class Declarations Are Not Hoisted
What you'll learn: You'll discover why you must declare a class before you can use it, unlike function declarations.
The Key Difference
You've learned that function declarations are "hoisted" to the top of their scope, meaning you can call them before they appear in your code. Classes don't work this way. Even though classes use the class keyword for declarations (similar to how functions use function), they behave more like let and const variables — they exist in a "temporal dead zone" until the line where they're declared is executed.
Why This Matters
With function declarations, this works fine:
const dog = new Animal('dog'); // ✓ Works!
function Animal(type) {
this.type = type;
}
But with class declarations, you'll get an error:
const dog = new Animal('dog'); // ❌ ReferenceError!
class Animal {
constructor(type) {
this.type = type;
}
}
You must declare the class first:
class Animal {
constructor(type) {
this.type = type;
}
}
const dog = new Animal('dog'); // ✓ Now it works!
Think of It This Way
Imagine classes as blueprints that must be fully drawn before the factory can use them. Function declarations are like pre-loaded templates that are available immediately, but class declarations need to be completely defined in order before they can be referenced.
This design choice encourages clearer, more predictable code organization where dependencies are explicit.
Key Takeaway: Class declarations are not hoisted — you must declare a class before creating instances or referencing it, just like variables declared with let or const.