Sub topic 1
Declaring a Class
A class is a template for creating objects that share the same shape and behavior. JavaScript has had the class keyword since ES2015. Before that, developers built the same structures by hand from constructor functions and prototypes. This chapter covers the two ways to write a class, a class declaration and a class expression. It also covers what can go inside a class body, how class names are scoped, and the syntax errors people hit most often. Later chapters explain each kind of class member in detail. Here the focus is the outer structure that holds them.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript variables (
let,const), functions, and arrow functions - Objects and property access with dot and bracket notation
- A basic idea of what
thisrefers to inside a function - Template literals and destructuring
- Running code in a browser console or with Node.js
You do not need to know anything about prototypes yet. The chapter "What Classes Really Are: Functions and Prototypes" covers them.
The Class Declaration
A class declaration starts with the class keyword, then a name, then a body in curly braces. By convention, class names use PascalCase (Point, ShoppingCart) so they stand out from ordinary functions and variables.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
const a = new Point(0, 0);
const b = new Point(3, 4);
console.log(a.distanceTo(b)); // 5This class has two members. The constructor runs once for each new object and sets up its properties. distanceTo is a method that every Point instance can call. The new keyword creates an instance, which is an object built from the class. The next two chapters cover constructors and methods in detail.
Look at the shape of the body. Members are written one after another with no commas between them. This differs from an object literal, where commas are required. Methods also use a shorthand: you write distanceTo(other) { ... } with no function keyword.
What Can Go Inside a Class Body
A class body can hold only member definitions. You cannot put arbitrary statements such as console.log(...) or if blocks directly in it. The table below lists every kind of member and the chapter that covers it.
| Member | Example syntax | Covered in |
|---|---|---|
| Constructor | `constructor(x) { ... }` | Constructors and Creating Instances with new |
| Instance method | `move(dx) { ... }` | Adding Behavior with Instance Methods |
| Public field | `count = 0;` | Declaring Public Instance Fields |
| Getter / setter | `get area() { ... }` | Computed Properties with Getters and Setters |
| Static method or field | `static create() { ... }` | Static Methods, Static Fields, and Static Blocks |
| Static block | `static { ... }` | Static Methods, Static Fields, and Static Blocks |
| Private field or method | `#secret = 1;` | Encapsulation with Private Fields and Methods |
A class with an empty body is also valid. class Empty {} declares a class whose instances start with no own properties.
Computed Member Names
A method name can be computed from an expression by wrapping the expression in square brackets, the same way you would in an object literal. This is how classes implement protocols keyed by symbols, such as Symbol.iterator.
const methodName = 'shout';
class Speaker {
[methodName](text) {
return text.toUpperCase();
}
*[Symbol.iterator]() {
yield 'one';
yield 'two';
}
}
const s = new Speaker();
console.log(s.shout('hi')); // "HI"
console.log([...s]); // [ 'one', 'two' ]The expression inside the brackets is evaluated once, when the class is defined. It is not evaluated again for each instance.
Class Expressions
A class can also be written as an expression and assigned to a variable, passed as an argument, or returned from a function. This works the same way as function expressions.
Anonymous Class Expressions
const Animal = class {
speak() {
return 'Some sound';
}
};
console.log(new Animal().speak()); // "Some sound"
console.log(Animal.name); // "Animal"The class has no name of its own, but JavaScript infers one from the variable it is assigned to, so Animal.name is "Animal". This name inference only happens when the anonymous class is assigned directly to a binding or property. It does not happen in other positions:
console.log((class {}).name); // ""
function makeAnon() {
return class {};
}
const Thing = makeAnon();
console.log(Thing.name); // ""Thing.name is empty because the class was created inside makeAnon, where it was not assigned to anything. The later assignment to Thing does not rename it. Empty names make stack traces and debugger output harder to read, which is one reason to give class expressions explicit names.
Named Class Expressions
A class expression can have its own name. That name is visible only inside the class body, which lets the class refer to itself reliably.
const Temperature = class Celsius {
describe() {
return `Instance of ${Celsius.name}`;
}
};
console.log(Temperature.name); // "Celsius"
console.log(new Temperature().describe()); // "Instance of Celsius"
console.log(typeof Celsius); // "undefined"Outside the class, only Temperature exists. Inside the body, Celsius always refers to this class, even if the outer variable is later reassigned. The inner name is read-only, so assigning Celsius = 1 inside a method throws a TypeError.
Classes Are Values
Every class, whether declared or written as an expression, is a value. You can store it in a data structure, pass it to a function, or build a new one on the fly.
function makeGreeter(greeting) {
return class Greeter {
greet(name) {
return `${greeting}, ${name}!`;
}
};
}
const Hello = makeGreeter('Hello');
const Hola = makeGreeter('Hola');
console.log(new Hello().greet('Ada')); // "Hello, Ada!"
console.log(new Hola().greet('Grace')); // "Hola, Grace!"
console.log(Hello === Hola); // false
const registry = { point: class { kind = 'point'; } };
console.log(new registry.point().kind); // "point"Each call to makeGreeter produces a separate class whose methods close over a different greeting. The chapter "Composing Behavior with Mixins" uses this same technique of functions that return classes.
Classes also work with modules. You can write export class Point { ... } for a named export or export default class { ... } for a default export.
Scoping Rules for Declarations
A class declaration creates a binding that is block-scoped, like let. It is not function-scoped like var.
{
class Local {}
console.log(typeof Local); // "function"
}
console.log(typeof Local); // "undefined"The name cannot be declared twice in the same scope:
class Widget {}
class Widget {} // SyntaxError: Identifier 'Widget' has already been declaredThe same error occurs if Widget was already declared with let, const, or class. Because the check runs at parse time, nothing in the file executes. You can still reassign the binding later with Widget = somethingElse, but doing so is almost always a mistake. A const holding a class expression prevents that.
Common Syntax Mistakes
These errors come from treating a class body like an object literal or like a function body.
class Broken {
a() { return 1; },
b() { return 2; }
}
// SyntaxError: Unexpected token ','The table lists the mistakes and their fixes.
| Mistake | What happens | Fix |
|---|---|---|
| Commas between members | `SyntaxError` | Remove the commas; semicolons are optional |
| `function` before a method name | `SyntaxError` | Write `name() { ... }` |
| A statement such as `console.log()` directly in the body | `SyntaxError` | Move it into a method, the constructor, or a `static {}` block |
| Two `constructor` methods | `SyntaxError: A class may only have one constructor` | Merge them; use default parameters for options |
| `name: value` pairs | `SyntaxError` | Use field syntax: `name = value;` |
| Reusing a class name in one scope | `SyntaxError` at parse time | Rename one, or use a nested block or module |
Exercise
What do the three console.log calls print, and why? const Shape = class Polygon { who() { return Polygon.name; } }; console.log(Shape.name); console.log(new Shape().who()); console.log(typeof Polygon);
Show answer
They print "Polygon", "Polygon", and "undefined". The inner name of a named class expression becomes the class's name property and is available inside the body. It is not created as a binding in the outer scope, so typeof Polygon outside the class is "undefined".
Exercise
Why does the following class fail to parse, and how do you fix it? class Timer { start: 0, function tick() { this.start++; } }
Show answer
The class body uses object-literal syntax (start: 0 and a comma) and the function keyword, and neither is allowed in a class body. Write it as class Timer { start = 0; tick() { this.start++; } }, with a public field declared with = and a method in shorthand syntax.
Exercise
A function returns class {} and you store the result with const Model = build();. What is Model.name, and how would you make it meaningful?
Show answer
Model.name is the empty string, because name inference only applies when an anonymous class is assigned directly to a binding, not when it comes back from a function call. Give the class expression an explicit name inside the function, for example return class Model {};.