Programming Language
JavaScript
OOPs
Class in OOP

Understanding Classes in JavaScript

In Object-Oriented Programming (OOP), a class is like a blueprint for creating objects. It defines what properties (data) and methods (actions) the objects created from it will have. In JavaScript, you can define classes using two main ways: class declarations and class expressions.

Class Declaration

A class declaration is a straightforward way to define a class. You use the class keyword followed by the name of the class. This is a common way to set up new types of objects.

Example:

// Define a class named Car
class Car {
  // Constructor is a special method for setting up new objects
  constructor(make, model, year) {
    this.make = make; // Property: the brand of the car
    this.model = model; // Property: the model of the car
    this.year = year; // Property: the year of the car
  }
 
  // Method: an action that the car can perform
  startEngine() {
    console.log(`${this.make} ${this.model} is starting.`);
  }
}
 
// Create an instance of the Car class
const myCar = new Car('Toyota', 'Corolla', 2020);
myCar.startEngine(); // Output: "Toyota Corolla is starting."

In this example:

  • Car is a class with a constructor that initializes the car's properties.
  • The startEngine method is an action the car can perform.
  • You create an object (myCar) from the Car class and use its methods and properties. Class Expression A class expression is another way to define a class, often used when you need to create a class dynamically or anonymously. It involves assigning a class to a variable.
// Define a class using a class expression
const Animal = class {
  constructor(name) {
    this.name = name; // Property: the name of the animal
  }
 
  // Method: an action that the animal can perform
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
};
 
// Create an instance of the Animal class
const myAnimal = new Animal('Lion');
myAnimal.speak(); // Output: "Lion makes a sound."

In this example:

  • Animal is a class created using a class expression.
  • The class has a constructor that sets up the animal's name and a speak method that describes what the animal does.
  • You create an object (myAnimal) from the Animal class and use its methods and properties.

Key Points to Remember

  • Class Declaration: This is a more common method for defining a class. It's clear and easy to use when you want to create named classes.
  • Class Expression: Useful for creating classes in a more flexible way, often when the class needs to be created dynamically or doesn’t need a specific name. Both methods for defining classes in JavaScript are valid. They help you structure your code by grouping related data and actions into single units, making it easier to manage and understand.