DevPath · Learn to code ESPTEN

Practical projects

Model with classes

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

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);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Process data with map, filter and reduceView the module →