When to Use Class Declarations vs Expressions
You'll learn: How to decide between class declarations and class expressions based on hoisting behavior and scope requirements.
The Core Difference
Both class declarations and expressions create classes, but they differ in when they become available and where they exist in your code:
Class declarations are named and exist in their entire scope, but unlike function declarations, they're not hoisted — you can't use them before the line they're declared.
Class expressions (named or anonymous) are typically assigned to variables or used immediately, giving you more control over scope and timing.
When to Use Each
Use Class Declarations When:
- You want a clear, named class that's the main feature of a module or file
- The class will be referenced throughout its scope
- You prefer straightforward, readable code structure
class User {
constructor(name) {
this.name = name;
}
}
const user = new User('Alice'); // ✓ Works
Use Class Expressions When:
- You need conditional class creation (choose different classes based on logic)
- You want to limit scope to a specific block or assignment
- You're passing a class as a value (to a function, or storing in an object)
const createClass = (includeMethod) => {
return includeMethod
? class { greet() { return 'Hi'; } }
: class { greet() { return 'Hello'; } };
};
Key Takeaway: Use class declarations for primary, well-defined classes in your code. Use class expressions when you need flexibility — conditional creation, limited scope, or treating classes as values. Both work the same after creation; the difference is when and how they're defined.