Explain it simply
Explain it simply
A class is like the design drawing in a car factory. The drawing says "every car has a brand, a model, a year and a speed, and it can accelerate and brake". You cannot drive the drawing itself, but you can build as many real cars from it as you like.
Every time you write new Car("Toyota", "Camry", 2023), a new car (an instance) rolls out, and a special method called the constructor fills in its starting data. Each car keeps its own speed, but all cars share the same accelerate() behavior.
Problem → Why → Solution
The problem: hand-copied objects drift apart
Suppose you write car objects one by one as object literals instead of using a class. The method must be copied into every object, and nothing checks that the property names match. In car2 below, speed was mistyped as sped, so accelerate() computes undefined + 50 and the speed becomes NaN.
const car1 = {
brand: "Toyota", speed: 0,
accelerate(amount) { this.speed += amount; },
};
const car2 = {
brand: "Honda", sped: 0, // typo
accelerate(amount) { this.speed += amount; }, // copied again
};
car2.accelerate(50);
console.log(car2.speed); // NaNWhy does this bug slip in so easily?
Each object has its own private idea of its shape, so the rule "every car has a speed" is not defined anywhere. Write this.speed = 0 once in a class constructor and every car comes out with the same shape, while the method is written exactly once.
Core concept: class, constructor and new
A class body can hold three kinds of member: the constructor, which runs once when an instance is created; instance methods, which every object can call; and static methods, which live on the class itself. Unlike an object literal, there are no commas between methods. All code inside a class body runs in strict mode automatically.
1. Create an empty object
new Car(...) starts with a brand-new {}.
2. Link its prototype
The object's prototype is set to Car.prototype, which is how it finds the class methods.
3. Run the constructor
The constructor is called with your arguments and this set to the new object.
4. Return the object
When the constructor finishes, the filled-in object becomes the value of the new expression.
Instance methods are not copied into each object; they are stored once on Car.prototype and every instance shares them. Static methods are for work that belongs to no single instance, such as comparing two cars or a factory that builds an instance from raw data. You call them on the class, Car.compare(a, b), and myCar.compare is undefined.
Class declarations are not hoisted the way function declarations are: using a class with new before its declaration line throws a ReferenceError. Calling a class without new is a TypeError too, which removes the forgotten-new bug from the constructor-function era.
Instead of writing this.speed = 0 in the constructor, you can declare speed = 0; as a class field at the top of the class body. Fields are added to the instance before the constructor body runs, which reads more clearly for starting values that do not depend on arguments. Either way the goal is the same: when the constructor finishes, the object must be ready to use.
- new Car(...) makes a fresh object
- constructor fills this with data
- Methods sit once on Car.prototype
- Static methods sit on Car itself
Data lives in each object, methods live once on the prototype, statics live on the class: three separate places.
General pattern
class ClassName {
#privateField = initialValue;
constructor(param) {
this.publicField = param;
}
instanceMethod() { /* uses this */ }
get computed() { return this.#privateField; }
static helper(a, b) { /* no instance needed */ }
}#privateField can only be read from inside the class. get computed() is a getter you read like a property, and static helper() is called as ClassName.helper(). Members are not separated by commas.
Example: a Car class
The Car class has a constructor, three instance methods that change or read a car's state, and one static method that compares two cars. The last two lines call compare() on the class itself, as Car.compare(...), not on a car: that is how a static method is used.
class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
this.speed = 0;
}
accelerate(amount) {
this.speed += amount;
return `${this.brand} speed: ${this.speed} km/h`;
}
brake() {
this.speed = 0;
return `${this.brand} stopped`;
}
getInfo() {
return `${this.year} ${this.brand} ${this.model}`;
}
static compare(car1, car2) {
return car1.year - car2.year;
}
}
const myCar = new Car("Toyota", "Camry", 2023);
console.log(myCar.getInfo());
console.log(myCar.accelerate(60));
console.log(myCar.accelerate(40));
console.log(myCar.brake());
const oldCar = new Car("Honda", "Civic", 2018);
console.log(Car.compare(oldCar, myCar));Code breakdown
- Lines 2-7
constructor(brand, model, year) {The three arguments are stored on this and speed starts at 0. Every car now comes out with exactly these four properties, so a typo like sped from the problem section cannot happen.
- Line 10
this.speed += amount;this is the object the method was called on, so myCar.accelerate(60) changes only myCar's speed. The second call goes from 60 to 100 because the object remembers its state between calls.
- Line 23
static compare(car1, car2) {Because of static, this method lives on Car itself and does not use this. It takes both cars as arguments and returns the difference in their years.
- Line 28
const myCar = new Car("Toyota", "Camry", 2023);new performs all four steps and stores the object the constructor filled in as myCar.
- Line 35
console.log(Car.compare(oldCar, myCar));The static method is called through the class name. 2018 - 2023 is -5, and a negative result means the first car is older. Because it returns negative or positive numbers, it also works directly as cars.sort(Car.compare).
2023 Toyota Camry
Toyota speed: 60 km/h
Toyota speed: 100 km/h
Toyota stopped
-5Private fields (#) and getters
Car's speed can still be set from outside with myCar.speed = 999. Put # in front of a field name and nothing outside the class body can read or write it; even writing account.#balance outside the class is a SyntaxError. To allow reading only, expose a getter (get balance()), and allow changes only through methods that validate them.
class BankAccount {
#balance = 0;
deposit(amount) {
if (amount <= 0) throw new RangeError("Deposit must be positive");
this.#balance += amount;
}
get balance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(500);
console.log(account.balance); // 500, read through the getter
console.log(Object.keys(account)); // [] - private fields are invisibleIn real projects
Where this shows up in real projects
In backend code it is very common to write an API client as a class. new ApiClient({ baseUrl, token }) receives the configuration once in its constructor, and methods such as getUser(id) and createOrder(data) read baseUrl and token from this. Keeping the token in a private #token field also makes it harder to leak by accident when the object is logged.
Static methods often act as factories: User.fromJSON(row) builds a User instance from a database row, and Date.now(), Array.from() and Number.isInteger() are built-in static methods. In a banking app, a BankAccount class hides #balance and its deposit() and withdraw() methods reject negative amounts or overdrafts, with tests written for exactly those invalid amounts.
Common mistakes
Common mistakes
1. Forgetting this. inside a method
Writing accelerate(amount) { speed += amount; } makes JavaScript look for a variable named speed; none exists, so you get "ReferenceError: speed is not defined". Instance properties are always reached through this.speed; being inside the class does not make them visible as variables.
2. Passing a method on its own as a callback
const stop = myCar.brake; stop();, or handing myCar.brake to any function that simply calls callback(), passes the bare brake function and loses its link to myCar. Class code is strict, so this is undefined and this.speed = 0 throws a TypeError. setTimeout(myCar.brake, 1000) is sneakier: setTimeout supplies its own this (window in a browser), so the wrong object is changed silently with no error. Pass () => myCar.brake() or myCar.brake.bind(myCar) instead.
3. Putting commas between methods
Out of object-literal habit, people write brake() {...}, getInfo() {...} with a comma, which is a SyntaxError in a class body. Class members are listed one after another without commas.
Best practices
Best practices
- Validate arguments in the constructor: instead of allowing new Car("", "", -1), throw a RangeError or TypeError.
- Use the constructor only to set state; move slow work such as network requests or file reads into a static async factory like await Car.load(id).
- Keep data that outsiders must not edit in a #field, expose a getter for reading, and allow changes only through methods that check them.
- Make a method static only when it needs no instance; anything that reads this belongs on the instance.
Mini challenge
Mini challenge: a Product class that protects its stock
Write a Product class for a shop. Keep the stock in a private field and let it decrease only through a sell method.
- constructor(name, price, stock) keeps stock in a #stock private field
- sell(quantity) returns "Only <n> <name> left" when stock is short, otherwise reduces it and returns "Sold <qty> <name>"
- get stock() lets callers read the remaining stock
- static cheapest(products) returns the lowest-priced product in an array
class Product {
// TODO: declare the private #stock field
constructor(name, price, stock) {
// TODO: store name and price publicly, stock privately
}
sell(quantity) {
// TODO: refuse when there is not enough stock, otherwise reduce it
}
// TODO: a getter named stock
// TODO: static cheapest(products)
}
// TODO: create Tea (2.5, 10) and Coffee (3, 4), sell 3 tea and 5 coffee,
// then print the tea stock and the cheapest product's nameExpected: The console prints: Sold 3 Tea Only 4 Coffee left Tea left: 7 Cheapest: Tea
Show hint
A private field must be declared at the top of the class body (#stock;) before the constructor can assign this.#stock = stock. For cheapest(), think about reduce((best, p) => (p.price < best.price ? p : best)).
Show solution
class Product {
#stock;
constructor(name, price, stock) {
this.name = name;
this.price = price;
this.#stock = stock;
}
sell(quantity) {
if (quantity > this.#stock) {
return `Only ${this.#stock} ${this.name} left`;
}
this.#stock -= quantity;
return `Sold ${quantity} ${this.name}`;
}
get stock() {
return this.#stock;
}
static cheapest(products) {
return products.reduce((best, p) => (p.price < best.price ? p : best));
}
}
const tea = new Product("Tea", 2.5, 10);
const coffee = new Product("Coffee", 3, 4);
console.log(tea.sell(3));
console.log(coffee.sell(5));
console.log(`Tea left: ${tea.stock}`);
console.log(`Cheapest: ${Product.cheapest([tea, coffee]).name}`);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class is a blueprint; its constructor sets up each new instance's state.
- new creates an empty object, links its prototype, runs the constructor and returns the object.
- Instance methods are shared on the prototype; static methods are called as ClassName.method().
- #fields are invisible outside the class, so expose data only through getters and validating methods.
MDN — Using Classes — MDN Web Docs