Lesson 1 of 6 · 10 min · 2 hands-on steps
Classes & Objects in JavaScript
Model real things with classes, the backbone of most large codebases.
Why classes?
As programs grow, you'll have many things that share the same shape and behavior: users, products, carts, orders. A class is a blueprint for them. Each object made from it (an instance) has its own data.
class Player {
constructor(name) {
this.name = name;
this.score = 0;
}
addPoints(n) {
this.score += n;
}
describe() {
return `${this.name} has ${this.score} points`;
}
}
const ada = new Player("Ada");
const bo = new Player("Bo");
ada.addPoints(10);
console.log(ada.describe());
console.log(bo.describe()); // Bo's score is separateconstructorruns once, when you writenew Player(...)thismeans "the object this method was called on"- Methods are functions that belong to the object
Classes vs plain objects
For a single config object, a plain { } is fine. Use a class when you'll create many objects with the same behavior, or when the data and the code that changes it belong together.
Static methods
Some functions belong to the class, not to any one object:
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
static fromFahrenheit(f) {
return new Temperature(((f - 32) * 5) / 9);
}
}
console.log(Temperature.fromFahrenheit(212).celsius);You've seen Python classes already. JavaScript's work the same way with different syntax:
constructorinstead of__init__, andthisinstead ofself.
🧪 Practice: 2 steps
0 / 2 doneStep 1 of 2 · A shopping cart
Complete the Cart class:
add(name, price)adds an item{ name, price }tothis.itemstotal()returns the sum of all pricescount()returns how many items are in the cart
class Cart {
constructor() {
this.items = [];
}
add(name, price) {
}
total() {
}
count() {
}
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Chainable methods
Make add return this so calls can be chained:
new Cart().add("A", 1).add("B", 2).total() → 3
class Cart {
constructor() {
this.items = [];
}
add(name, price) {
this.items.push({ name, price });
}
total() {
return this.items.reduce((s, i) => s + i.price, 0);
}
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What does the constructor do?
Inside a method, what does this refer to?
Create a free account to track your progress.