class expression
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2016.
Theclass
keyword can be used to define a class inside an expression.
You can also define classes using theclass
declaration.
Try it
const Rectangle = class { constructor(height, width) { this.height = height; this.width = width; } area() { return this.height * this.width; }};console.log(new Rectangle(5, 8).area());// Expected output: 40
Syntax
class { // class body}class name { // class body}
Note:Anexpression statement cannot begin with the keywordclass
to avoid ambiguity with aclass
declaration. Theclass
keyword only begins an expression when it appears in a context that cannot accept statements.
Description
Aclass
expression is very similar to, and has almost the same syntax as, aclass
declaration. As withclass
declarations, the body of aclass
expression is executed instrict mode. The main difference between aclass
expression and aclass
declaration is theclass name, which can be omitted inclass
expressions to createanonymous classes. Class expressions allow you to redefine classes, while redeclaring a class usingclass
declarations throws aSyntaxError
. See also the chapter aboutclasses for more information.
Examples
A basic class expression
This is just an anonymous class expression which you can refer to using the variableFoo
.
const Foo = class { constructor() {} bar() { return "Hello World!"; }};const instance = new Foo();instance.bar(); // "Hello World!"Foo.name; // "Foo"
Named class expressions
If you want to refer to the current class inside the class body, you can create anamed class expression. The name is only visible within the scope of the class expression itself.
const Foo = class NamedFoo { constructor() {} whoIsThere() { return NamedFoo.name; }};const bar = new Foo();bar.whoIsThere(); // "NamedFoo"NamedFoo.name; // ReferenceError: NamedFoo is not definedFoo.name; // "NamedFoo"
Specifications
Specification |
---|
ECMAScript® 2026 Language Specification # sec-class-definitions |