Why Classes?

Sophomore Year, page 1 of 11. A one-minute read.

Imagine you're building a game with lots of characters. Each character has a name, some health, a level, and can do things like attack and heal. You already know how to make one with an object:

JavaScript
const hero = {
  name: "Mia the Brave",
  health: 100,
  level: 1,
  attack() {
    console.log(`${this.name} swings her sword! ⚔️`);
  },
};

hero.attack();

It prints

Mia the Brave swings her sword! ⚔️

Great. Now make twenty more characters. And a hundred enemies. Are you going to copy and paste that object 120 times, changing the name each time? What if you want to add a new heal method to all of them later? You'd have to edit 120 objects.

What you really want is a blueprint: a single description of "what a character is," which you can then use to stamp out as many characters as you need. That's exactly what a class is.

Think of it like thisThe cookie cutter

A class is like a cookie cutter. The cutter itself isn't a cookie. You can't eat it (please don't try). But you can use it to make as many cookies as you like, and they'll all have the same shape. Each cookie can still be different, though: one has chocolate chips, one has sprinkles. In programming, the class is the cookie cutter, and each cookie you make with it is called an instance (or simply an object).

A class is a blueprint (the cutter). Each object made from it is an instance (a cookie).

Organizing code around objects that bundle together data (properties) and behavior (methods) is called object-oriented programming, or OOP. It's one of the most popular ways to structure large programs, and you'll find it in almost every programming language: Java, Python, C#, C++, Swift, PHP, and of course, JavaScript.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning