Model a system with classes
When a project handles state that changes (a task list, a cart, an inventory), classes help group the data and the operations that act on it.
class Cart {
constructor() {
this.items = [];
}
add(product, price) {
this.items.push({ product, price });
}
remove(product) {
this.items = this.items.filter((i) => i.product !== product);
}
total() {
return this.items.reduce((acc, i) => acc + i.price, 0);
}
get count() {
return this.items.length;
}
}
const cart = new Cart();
cart.add("book", 20);
cart.add("coffee", 5);
console.log(cart.total()); // 25
console.log(cart.count); // 2
Best practices
- Keep the internal state consistent: modify it only through methods.
- Each method should have a clear responsibility.
- Use getters for derived values (
count,total).
This way of thinking — data + behavior together — is the foundation of object-oriented programming.
Examples
A class with state and methods
class Counter {
constructor() { this.value = 0; }
up() { this.value++; return this; }
down() { this.value--; return this; }
}
const c = new Counter();
c.up().up().down();
console.log("Final value:", c.value);