Why This Matters
You have learned to create individual objects with properties and methods. But what if you need to create hundreds of similar objects — users, products, game characters? A class is a blueprint that defines the structure and behavior shared by all objects of a certain type.
Classes are the foundation of object-oriented programming (OOP), the most widely-used programming paradigm. React components, database models, API controllers, game entities — all are typically organized as classes or class-like patterns.
Define Terms
Visual Model
The full process at a glance. Click Start tour to walk through each step.
Classes are blueprints. Instances are objects created from those blueprints. Inheritance lets classes build on each other.
Code Example
// Defining a class
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I am ${this.name}`;
}
isAdult() {
return this.age >= 18;
}
}
// Creating instances
const alice = new User("Alice", 28);
const bob = new User("Bob", 15);
console.log(alice.greet()); // Hi, I am Alice
console.log(bob.isAdult()); // false
// Inheritance
class Admin extends User {
constructor(name, age, level) {
super(name, age); // call parent constructor
this.level = level;
}
greet() {
return `${super.greet()} [Admin L${this.level}]`;
}
}
const admin = new Admin("Carol", 35, 2);
console.log(admin.greet()); // Hi, I am Carol [Admin L2]
console.log(admin.isAdult()); // true (inherited)
console.log(admin instanceof User); // trueInteractive Experiment
Try these exercises:
- Create a
Rectangleclass withwidthandheightproperties, and anarea()method. - Add a
perimeter()method that returns2 * (width + height). - Create a
Squareclass that extendsRectangle— its constructor takes one side length. - Make 5 different rectangles and store them in an array. Use
.map()to get an array of their areas. - What does
instanceoftell you about objects and their class hierarchy?
Quick Quiz
Coding Challenge
Create a class called `BankAccount` with: a constructor that takes an initial balance, a `deposit(amount)` method, a `withdraw(amount)` method that returns 'Insufficient funds' (as a string) if the balance is too low, and a `getBalance()` method.
Real-World Usage
Classes structure code in nearly every large application:
- React components: Class components use
extends React.Componentwith lifecycle methods. - Database models: ORMs like Sequelize and Django define table schemas as classes.
- Game development: Characters, enemies, items, and levels are all classes.
- Design patterns: Singletons, factories, observers — all classic patterns use classes.
- Standard libraries: Array, Map, Set, Date, Error — built-in classes you use every day.