What is Class Expression in JavaScript: Simple Explanation and Example
class expression in JavaScript is a way to define a class inside an expression, which can be anonymous or named. Unlike class declarations, class expressions can be assigned to variables, passed as arguments, or used anywhere an expression is allowed.How It Works
Think of a class expression like creating a blueprint for an object right where you need it, instead of giving it a fixed name upfront. It’s like writing a recipe on the spot and handing it to someone, rather than posting it on a board with a title.
In JavaScript, a class expression can be anonymous (without a name) or named. You can assign this class to a variable or use it directly. This flexibility lets you create classes dynamically or keep them private inside a function.
Because class expressions are expressions, they can be used anywhere JavaScript expects a value, such as inside function calls or conditional statements.
Example
This example shows a class expression assigned to a variable and used to create an object. It also shows an anonymous class expression used directly.
const Person = class { constructor(name) { this.name = name; } greet() { return `Hello, my name is ${this.name}`; } }; const john = new Person('John'); console.log(john.greet()); // Anonymous class expression used directly const dog = new (class { bark() { return 'Woof!'; } })(); console.log(dog.bark());
When to Use
Use class expressions when you want to create a class without naming it globally or when you need to define a class dynamically inside another expression. For example, you might use a class expression inside a function to keep the class private or pass a class as an argument to another function.
They are helpful in modular code, where you want to limit the scope of a class or create quick one-off classes without cluttering the global namespace.
Key Points
- Class expressions can be anonymous or named.
- They are expressions and can be assigned, passed, or used inline.
- They provide flexibility and scope control compared to class declarations.
- Useful for dynamic or private class definitions.