Table of contents
1.
Introduction
2.
Class in JavaScript
2.1.
Key Features of JavaScript Classes
3.
Creating a Simple Class
4.
Constructor to Initialize Objects
4.1.
Key Points About Constructors
5.
Creating Multiple Objects with a Class
6.
Benefits of Using Classes in JavaScript
7.
Browser Support
8.
Frequently Asked Questions
8.1.
What is the difference between a class and an object in JavaScript?
8.2.
Can a JavaScript class have more than one constructor?
8.3.
What happens if I don’t include a constructor in a JavaScript class?
9.
Conclusion
Last Updated: Dec 22, 2024
Easy

JavaScript Classes

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript classes are a fundamental feature that simplifies object-oriented programming. Introduced in ES6, classes in JavaScript provide a cleaner and more structured way to create objects and manage their behavior. Whether you're building dynamic web pages or working on complex applications, understanding classes can make your code more efficient and organized. 

JavaScript Classes

In this article, we will discuss what classes are, how to create them, and how to use constructors and objects effectively.

Class in JavaScript

In JavaScript, a class is essentially a blueprint for creating objects. It encapsulates data (properties) and methods (functions) that operate on that data. Instead of defining objects individually, you can use a class to streamline object creation and management.

Here’s a simple representation of a class:

class ExampleClass {
    constructor(property) {
        this.property = property; // Define a property
    }
    showProperty() {
        console.log(this.property); // Define a method
    }
}

Key Features of JavaScript Classes

  • Encapsulation: Group related properties and methods together.
     
  • Reusability: Use a single class to create multiple objects.
     
  • Readability: Code looks cleaner and easier to manage.

Creating a Simple Class

A class in JavaScript is defined using the class keyword. The class contains a constructor to initialize properties and methods to define behavior.

Here’s an example of creating a simple class:

class Student {
    constructor(name, age) {
        this.name = name; // Assigning name property
        this.age = age;   // Assigning age property
    }


    // Method to display student details
    displayDetails() {
        console.log(`Name: ${this.name}, Age: ${this.age}`);
    }
}


// Creating an object of the Student class
const student1 = new Student("Alice", 20);
student1.displayDetails();
You can also try this code with Online Javascript Compiler
Run Code


Explanation:

  1. The Student class is defined with a name and age property.
     
  2. The constructor initializes these properties when a new object is created.
     
  3. The displayDetails method prints the object's details to the console.

Constructor to Initialize Objects

The constructor is a special method in JavaScript classes. It is automatically invoked when you create a new object from a class. It’s typically used to initialize the properties of the object.

Here’s an example:

class Car {
    constructor(make, model, year) {
        this.make = make;    // Car brand
        this.model = model;  // Car model
        this.year = year;    // Manufacturing year
    }


    displayCarInfo() {
        console.log(`Car: ${this.make} ${this.model}, Year: ${this.year}`);
    }
}
// Creating objects of the Car class
const car1 = new Car("Toyota", "Corolla", 2021);
const car2 = new Car("Honda", "Civic", 2020);
// Displaying information
car1.displayCarInfo(); 
car2.displayCarInfo();
You can also try this code with Online Javascript Compiler
Run Code


Output:

Car: Toyota Corolla, Year: 2021
Car: Honda Civic, Year: 2020

Key Points About Constructors

  • Only one constructor is allowed per class.
     
  • If you don’t define a constructor, JavaScript adds a default constructor.
     
  • You can pass arguments to a constructor to initialize different object properties.

Creating Multiple Objects with a Class

One of the most powerful features of classes is the ability to create multiple objects using the same blueprint. This reduces redundancy and improves maintainability.

Example:

class Employee {
    constructor(id, name, department) {
        this.id = id;             // Employee ID
        this.name = name;         // Employee Name
        this.department = department; // Department
    }
    getDetails() {
        return `ID: ${this.id}, Name: ${this.name}, Department: ${this.department}`;
    }
}
// Creating multiple objects
const emp1 = new Employee(101, "John", "HR");
const emp2 = new Employee(102, "Jane", "Finance");
const emp3 = new Employee(103, "Sam", "IT");

// Displaying details
console.log(emp1.getDetails()); 
console.log(emp2.getDetails()); 
console.log(emp3.getDetails()); 
You can also try this code with Online Javascript Compiler
Run Code


Output

ID: 101, Name: John, Department: HR
 ID: 102, Name: Jane, Department: Finance
 ID: 103, Name: Sam, Department: IT

 

Explanation:

  1. The Employee class is defined with properties like id, name, and department.
     
  2. Multiple employee objects are created using this class.
     
  3. Each object has unique data but shares the same methods, promoting code reuse.

Benefits of Using Classes in JavaScript

  • Encapsulation: Classes allow you to encapsulate related data & functions into a single unit. This helps keep your code modular & reduces the risk of naming conflicts.
     
  • Reusability: Once you define a class, you can create multiple instances of it with different data. This promotes code reuse & saves time.
     
  • Inheritance: Classes support inheritance, allowing you to create new classes based on existing ones. This enables you to define common properties & methods in a base class & extend them in subclasses, promoting code reuse & hierarchical organization.
     
  • Readability: Classes provide a clear & structured way to organize your code. By grouping related functionality together, classes make your code more readable & easier to understand.
     
  • Maintainability: As your codebase grows, classes help keep it maintainable by providing a clear structure & encapsulating related logic. This makes it easier to locate & modify specific parts of your code without affecting the rest.

Browser Support

JavaScript classes are supported in all modern web browsers, like:

  • Chrome (version 49+)
  • Firefox (version 45+)
  • Safari (version 9+)
  • Opera (version 36+)
  • Edge (version 13+)
  • Internet Explorer (not supported)

Frequently Asked Questions

What is the difference between a class and an object in JavaScript?

A class is a blueprint, while an object is an instance of that class. The class defines properties and methods, and objects use those definitions.

Can a JavaScript class have more than one constructor?

No, JavaScript allows only one constructor per class. Adding multiple constructors will result in an error.

What happens if I don’t include a constructor in a JavaScript class?

If no constructor is provided, JavaScript adds a default constructor that does nothing or simply calls the parent class's constructor in case of inheritance.

Conclusion

JavaScript classes are an essential tool for modern programming. They provide a structured way to create and manage objects, making your code more readable and reusable. By learning how to use classes, constructors, and methods, you can simplify complex programs and write efficient code. Whether you're a beginner or an experienced developer, mastering JavaScript classes is a valuable skill.

Live masterclass