A class is a blueprint for creating objects that share the same structure and behaviour. Each object made from it is an instance.
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
greet() {
return `Hi, I am ${this.name}`;
}
}
const maya = new User("Maya", "maya@example.com");
const arjun = new User("Arjun", "arjun@example.com");
console.log(maya.greet()); // → Hi, I am Maya
console.log(arjun.name); // → Arjun
console.log(maya instanceof User); // → true
The parts
class User { ... }declares the class.constructor(...)runs when you create an instance withnew. It sets up the object’s data.thisis the new object.- Methods (
greet()) are shared by every instance. new User(...)creates an instance. Forgettingnewthrows an error.
Methods and this
Inside a method, this is the instance the method was called on, just like object methods. The same warning applies: if you detach a method and call it alone, this is lost.
class Counter {
count = 0;
increment() {
this.count++;
return this; // returning this allows chaining
}
}
const counter = new Counter();
console.log(counter.increment().increment().count); // → 2
Why use classes?
A class groups data and the functions that work on it in one place, and lets you create many similar objects. They suit things with identity and behaviour: a shopping cart, a timer, a game character, a form field.
class Cart {
items = [];
add(name, price) {
this.items.push({ name, price });
return this;
}
total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}
const cart = new Cart().add("Book", 12).add("Pen", 3);
console.log(cart.total()); // → 15
Class declarations are not hoisted like functions
try {
const early = new Later(); // error on purpose: cannot access before initialization
} catch (error) {
console.log(error.name); // → ReferenceError
}
class Later {}
Define a class before you use it.
Classes run in strict mode
Code inside a class body is always strict mode.
Are classes necessary?
No. Plain objects and functions solve many problems well, and JavaScript code is often written without classes. They are one tool. Many libraries and frameworks use them, so you need to read and write them.
Under the hood
Classes are a cleaner syntax over JavaScript’s existing prototype system. They do not replace it. See Classes and Prototypes.
Naming
ShoppingCart), and instances use camelCase (cart).