Class Expressions

Deep dive into the basics of class expressions and learn how to create a class using class expressions.

Class expressions are useful to create dynamic classes at runtime based on, for example, properties you read from a file, database, or user-provided input. Imagine creating a class factory function that will create and return a class; this is a good place to use a class expression.

Difference between class expression and class statement

JavaScript supports both a class statement, which you use to define a class, and a class expression. The two key differences between a class expression and a class statement are:

  1. The class name is optional for class expressions but required for class statements.

  2. The class expression should be treated as an expression; that is, it should be returned, passed to another function, or stored in a variable.

Class statements are more common than class expressions, but the latter is useful to create classes dynamically.

Creating class using class expressions

Let’s create a function that acts as a class factory; meaning it dynamically creates and returns a class with fields provided as parameters to the call.

Get hands-on with 1400+ tech skills courses.