When Should You Use Classes?

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

Classes are a great tool, but they're not the only tool. JavaScript is flexible, and lots of excellent JavaScript code uses few or no classes at all.

Use a class when...Use plain objects and functions when...
You need many objects of the same type, with the same methodsYou just need to hold some data
Objects have state that changes over time, with rules about howYour functions just take inputs and return outputs
You want encapsulation (private data)Simple is enough
You're modeling things (users, characters, accounts, shapes)You're transforming data (like the array methods in Grade 10)

Many developers mix both styles: classes for the "things" in their app, and plain functions for processing data. That's perfectly fine!

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