Class Expressions: Named and Anonymous
You'll learn how to treat classes as values by assigning them to variables or passing them around like any other expression.
What Are Class Expressions?
Just like functions, classes don't have to be declared with a name at the top level. You can create a class expression—a class defined as part of an expression and assigned to a variable or passed directly as a value.
Think of it like the difference between a function declaration (function greet() {}) and a function expression (const greet = function() {}). Classes work the same way.
Anonymous Class Expressions
An anonymous class expression has no name after the class keyword:
const Rectangle = class {
constructor(width, height) {
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
};
const rect = new Rectangle(5, 10);
console.log(rect.getArea()); // 50
The class itself has no name—Rectangle is just the variable holding it.
Named Class Expressions
A named class expression includes a name after class:
const Square = class Shape {
constructor(side) {
this.side = side;
}
};
const sq = new Square(4);
console.log(sq instanceof Square); // true
The internal name (Shape) is only visible inside the class body—useful for recursion or debugging. Outside, you use the variable name (Square).
Why Use Class Expressions?
Class expressions shine when you need to:
- Pass a class as an argument to a function
- Return a class from a factory function
- Conditionally create different classes
Key Takeaway: Class expressions let you assign classes to variables or pass them as values, just like function expressions—choose anonymous for simplicity or named for internal self-reference.