01 / 21

Defining Classes
in JavaScript

Learn how to create blueprints for objects using the class syntax: constructors, methods, and instances that bring your code to life.

JavaScript

What Is a Class?

A class is a blueprint or template that describes the properties (data) and methods (behavior) an object will have. Instead of writing the same object structure over and over, you define a class once and create as many objects from it as you need.

Key Vocabulary

Class
A template that defines properties and methods for creating objects.
Constructor
A special method called automatically when a new instance is created.
Instance
A specific object built from a class using the new keyword.
Method
A function defined inside a class that describes what instances can do.
this
A keyword inside a class that refers to the current instance of the class.

Why Do Classes Matter?

Without classes, you must manually build every object with the same repeated structure. Classes solve three critical problems:

1
Reusability: define the structure once, create unlimited instances.
2
Organization: group related data and behavior together in one place.
3
Maintainability: change the class once, and every instance benefits from the update.

Anatomy of a Class

class Dog { constructor ( name , breed ) { this . name = name ; this . breed = breed ; } bark () { return `${ this . name } says Woof!` ; } } CONSTRUCTOR METHOD CLASS NAME

The Constructor Method

The constructor is a special method that runs automatically when you create a new instance with the new keyword. Its job is to set initial property values using this.

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
}

Classes vs Object Literals

Class Object Literal
Syntax class Dog { ... } { name: "Rex" }
Reusable? Yes: create many instances No: one-off object
Constructor Built-in constructor method None
Methods Shared on prototype Copied per object
Best for Multiple similar objects Single configuration/data

How to Define a Class

1
Declare the class using the class keyword followed by a capitalized name and curly braces.
2
Write the constructor to accept parameters and assign them to this properties.
3
Add methods below the constructor: no function keyword, no commas between them.
4
Create instances with new ClassName(args) and store in variables.
5
Call methods on the instance: instance.methodName().

Example 1: Student Class

class Student {
  constructor(name, grade) {
    this.name = name;
    this.grade = grade;
  }

  introduce() {
    return `Hi, I'm ${this.name} in grade ${this.grade}.`;
  }
}

const alice = new Student("Alice", 10);
alice.introduce(); // "Hi, I'm Alice in grade 10."

Example 2: BankAccount

class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
  }

  deposit(amount) {
    this.balance += amount;
    return this.balance;
  }

  withdraw(amount) {
    if (amount > this.balance) {
      return "Insufficient funds";
    }
    this.balance -= amount;
    return this.balance;
  }
}

Example 3: TaskList with Arrays

class TaskList {
  constructor(title) {
    this.title = title;
    this.tasks = []; // initialize empty array
  }

  addTask(task) {
    this.tasks.push(task);
  }

  getCount() {
    return this.tasks.length;
  }

  summarize() {
    return `${this.title}: ${this.getCount()} tasks`;
  }
}

From Class to Instances

CLASS: Dog properties: name, breed methods: bark() new new new rex name: "Rex" breed: "Labrador" bark() → "Rex says Woof!" luna name: "Luna" breed: "Poodle" bark() → "Luna says Woof!" max name: "Max" breed: "Beagle" bark() → "Max says Woof!"

Understanding this

Inside a class, this always refers to the specific instance that called the method. It is the bridge between the class blueprint and the actual object.

class Cat {
  constructor(name) {
    this.name = name; // "this" = the new Cat
  }
  greet() {
    return `Meow, I'm ${this.name}`;
  }
}

const whiskers = new Cat("Whiskers");
whiskers.greet(); // "this" = whiskers
// "Meow, I'm Whiskers"

Methods Working Together

class Counter {
  constructor() {
    this.count = 0;
  }

  increment() {
    this.count++;
  }

  decrement() {
    this.count--;
  }

  getStatus() {
    return `Count is ${this.count}`;
  }
}

const c = new Counter();
c.increment();
c.increment();
c.getStatus(); // "Count is 2"

Common Mistakes

✕ Forgetting "new"
Writing Dog("Rex") without new does not create an instance: it either throws an error or returns undefined.
✕ Missing "this"
Writing name = name in the constructor creates a local variable instead of attaching it to the instance. Always use this.name.
✕ Adding Commas
Placing commas between methods (like object literals) causes a syntax error. Methods are separated by whitespace only.
✕ Lowercase Class Name
Using class dog instead of class Dog breaks convention. Capitalize class names to distinguish them from variables.

Class Syntax Summary

Concept Syntax Purpose
Declare a class class Name { } Create a reusable blueprint
Constructor constructor(params) Initialize instance properties
Set a property this.prop = value Attach data to the instance
Define a method methodName() { } Add behavior to instances
Create an instance new Name(args) Build an object from the class
Call a method instance.method() Execute behavior on an instance

Question 1 of 5

Which keyword is used inside a class to refer to the current instance?

Question 2 of 5

What happens if you call a class without the new keyword?

Question 3 of 5

What does myCar.age() return?

Question 4 of 5

How are methods separated inside a class body?

Question 5 of 5

What does rock.count() return after the code above runs?