What is a Class in JavaScript?
Creating reusable objects with JavaScript class syntax.
When you need to create many objects that share the same shape and behavior, like users, products or shopping carts, writing each one by hand gets old fast. A class gives you a blueprint you can use to create as many of those objects as you need.
A class is a template for creating objects. It bundles the data an object holds with the methods that work on that data.
Under the hood, classes are built on
prototypal inheritance.
The class syntax is just a cleaner way to write it.
Basic class syntax
A class is declared with the class keyword. The constructor method runs when
you create a new instance with new, and it's where you set up the object's
properties.
class User {constructor(name, email) {this.name = namethis.email = email}greet() {return `Hi, I'm ${this.name}`}}const user = new User("John", "john@example.com")user.greet() // "Hi, I'm John"user instanceof User // true
Methods like greet are shared by every instance instead of being copied onto
each one. Unlike function declarations, classes aren't hoisted, so you have to
declare a class before you use it.
Getters and setters
Getters and setters let you run code when a property is read or written, while still using it like a normal property.
class User {constructor(firstName, lastName) {this.firstName = firstNamethis.lastName = lastName}get fullName() {return `${this.firstName} ${this.lastName}`}set fullName(value) {const [firstName, lastName] = value.split(" ")this.firstName = firstNamethis.lastName = lastName}}const user = new User("John", "Smith")user.fullName // "John Smith"user.fullName = "Jane Doe"user.firstName // "Jane"
Notice there are no parentheses. user.fullName calls the getter for you.
Static methods and properties
A static member belongs to the class itself, not to its instances. These are
handy for helper functions or for creating instances in a specific way.
class User {static roles = ["admin", "editor", "viewer"]static fromJSON(json) {const { name, email } = JSON.parse(json)return new User(name, email)}constructor(name, email) {this.name = namethis.email = email}}User.roles // ["admin", "editor", "viewer"]const user = User.fromJSON('{"name":"John","email":"john@example.com"}')user.name // "John"user.fromJSON // undefined
Private fields and methods
Prefix a field or method with # to make it private. Private members can only
be used inside the class body. Trying to reach them from the outside is a syntax
error.
Note: Class fields, including static and private # fields, are a Stage 3
proposal. Chrome, Edge and Node already support all of them, and Firefox and
Safari support some of them with the rest on the way. Until then, Babel can
compile them for older browsers.
class Counter {#count = 0increment() {this.#count++this.#log()}get value() {return this.#count}#log() {console.log(`Count is now ${this.#count}`)}}const counter = new Counter()counter.increment() // console: Count is now 1counter.value // 1counter.count // undefined
counter.#count outside the class won't even run. This keeps the internal state
safe from code you don't control. count = 0 written without the # is a
public class field, which is a quick way to set a default without a
constructor.
Inheritance with extends and super
A class can inherit from another class with extends. Inside the child class,
super() calls the parent's constructor, and super.method() calls a parent
method.
class Animal {constructor(name) {this.name = name}speak() {return `${this.name} makes a sound`}}class Dog extends Animal {constructor(name, breed) {super(name)this.breed = breed}speak() {return `${super.speak()}. Woof!`}}const rex = new Dog("Rex", "Labrador")rex.speak() // "Rex makes a sound. Woof!"rex instanceof Animal // true
Important! In a child class you must call super() before using this in
the constructor, otherwise you'll get a ReferenceError.
A practical example
Putting this all together, here's a small shopping cart:
class Cart {#items = []static TAX_RATE = 0.08add(name, price, quantity = 1) {this.#items.push({ name, price, quantity })return this}remove(name) {this.#items = this.#items.filter((item) => item.name !== name)return this}get count() {return this.#items.reduce((total, item) => total + item.quantity, 0)}get subtotal() {return this.#items.reduce((total, item) => total + item.price * item.quantity,0)}get total() {return Number((this.subtotal * (1 + Cart.TAX_RATE)).toFixed(2))}}const cart = new Cart()cart.add("Shirt", 20, 2).add("Hat", 15).remove("Hat")cart.count // 2cart.subtotal // 40cart.total // 43.2
The items are private so nothing outside the cart can change them directly.
Returning this from add and remove lets you chain calls, and the getters
keep the totals up to date without storing extra state.
Summary
Classes give you a clean way to group data and behavior together. Use getters
for computed values, static for class-level helpers, # for anything that
should stay internal, and extends when one class is a more specific version of
another.
Have some feedback on this post? .