Classes| Dataplexa

Classes

In the previous lesson, you learned the basics of Object-Oriented Programming (OOP).

In this lesson, we introduce classes, a cleaner and more structured way to create objects in modern JavaScript.


What Is a Class?

A class is a blueprint for creating objects.

It defines:

  • What data an object should have
  • What actions an object can perform

Think of a class as a template, and objects as instances created from it.


Why Classes Were Introduced

Before ES6, JavaScript used constructor functions and prototypes directly.

Classes were added to:

  • Improve readability
  • Make OOP easier to understand
  • Align JavaScript with other OOP languages

Under the hood, JavaScript still uses prototypes. Classes are syntactic sugar.


Creating a Class

A class is created using the class keyword.


class User {
  constructor(name, role) {
    this.name = name;
    this.role = role;
  }
}
  

The constructor runs automatically when a new object is created.


Creating Objects from a Class

Objects created from a class are called instances.


let user1 = new User("Alex", "Developer");
let user2 = new User("Sara", "Designer");
  

Each instance has its own data.


Adding Methods

Methods define behavior for class objects.


class User {
  constructor(name, role) {
    this.name = name;
    this.role = role;
  }

  greet() {
    return `Hello, I am ${this.name}`;
  }
}
  

Methods are shared across all instances.


Real-World Example

Modeling a simple employee system:


class Employee {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }

  getDetails() {
    return `${this.name} works in ${this.department}`;
  }
}
  

This pattern is very common in applications.


Classes vs Objects

  • A class is a blueprint
  • An object is created from a class
  • One class can create many objects

Common Beginner Mistakes

  • Forgetting the new keyword
  • Using arrow functions for class methods
  • Confusing classes with plain objects

Classes provide structure, not magic.


Thumb Rules

  • Use classes to model real-world entities
  • Keep classes focused on one responsibility
  • Prefer readable class design
  • Understand what happens behind the scenes

What Comes Next?

Now that you understand classes, the next step is learning how JavaScript shares behavior between objects.

In the next lesson, we will explore prototypes.