JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Class Intro


JavaScript classes are a modern way to create objects and work with object-oriented programming concepts such as encapsulation, inheritance, and methods. Classes provide a clean and structured approach to defining blueprints for objects, making your code more organized, readable, and maintainable. They are a syntactical improvement over constructor functions, offering a more intuitive way to create and manage objects.

In this tutorial, you will learn about JavaScript classes, how to define and use them, practical examples, common mistakes, best practices, and real-world applications.

Why Classes Are Important

Classes are important in JavaScript because they allow you to:

  • Create multiple objects with similar structures and behaviors

  • Encapsulate data and methods within a single, reusable blueprint

  • Implement object-oriented programming principles efficiently

  • Make code more organized and maintainable

  • Enable inheritance to extend functionality from other classes

Without classes, developers would need to rely on constructor functions and prototypes, which can become cumbersome and harder to manage in complex applications.

Defining a Class

A class in JavaScript is defined using the class keyword, followed by the class name and a body enclosed in curly braces. By convention, class names start with a capital letter.

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

    greet() {
        console.log("Hello, my name is " + this.name);
    }
}

Here, constructor is a special method used to initialize new objects. The greet method is a class method that can be called on any instance of the class.

Creating Objects from a Class

Once a class is defined, you can create new objects using the new keyword:

const student1 = new Student("Aarushi", 20, "JavaScript");
const student2 = new Student("Priya", 22, "React");

console.log(student1.name); // Aarushi
student2.greet();           // Hello, my name is Priya

Each object created from the class has its own set of properties, while methods defined in the class are shared across instances.

Class Methods

Class methods are functions defined inside the class that can interact with instance properties using this. They allow encapsulated behavior within the class.

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

    celebrateBirthday() {
        this.age += 1;
        console.log(this.name + " is now " + this.age + " years old");
    }
}

const student = new Student("Saanvi", 21);
student.celebrateBirthday(); // Saanvi is now 22 years old

Methods help keep related behavior and data together, making the class a self-contained unit.

Getters and Setters

JavaScript classes also support getters and setters, which provide controlled access to object properties.

class Student {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }

    get name() {
        return this._name;
    }

    set age(value) {
        if (value > 0) {
            this._age = value;
        } else {
            console.log("Invalid age");
        }
    }
}

const student = new Student("Isha", 22);
console.log(student.name); // Isha
student.age = 23;
console.log(student._age); // 23

Getters and setters provide a layer of validation and encapsulation for properties.

Static Methods

Static methods are functions defined on the class itself rather than on instances. They are useful for utility functions related to the class but not specific to an object.

class Student {
    static schoolInfo() {
        console.log("All students belong to XYZ School");
    }
}

Student.schoolInfo(); // All students belong to XYZ School

Static methods cannot be called on individual objects; they are only accessible via the class.

Inheritance

Classes in JavaScript support inheritance using the extends keyword. This allows one class to inherit properties and methods from another class.

class Person {
    constructor(name) {
        this.name = name;
    }

    greet() {
        console.log("Hello, my name is " + this.name);
    }
}

class Teacher extends Person {
    constructor(name, subject) {
        super(name);
        this.subject = subject;
    }

    teach() {
        console.log(this.name + " is teaching " + this.subject);
    }
}

const teacher = new Teacher("Saanvi", "Math");
teacher.greet(); // Hello, my name is Saanvi
teacher.teach(); // Saanvi is teaching Math

The super keyword calls the constructor of the parent class, enabling inheritance of properties and methods.

Common Mistakes

  • Forgetting to use new when creating an instance, which causes errors

  • Misusing this inside class methods, especially in callbacks

  • Overwriting methods or properties accidentally

  • Confusing static methods with instance methods

  • Forgetting to call super() in subclasses

Best Practices

  • Use descriptive class names with capitalization

  • Keep classes focused on a single responsibility

  • Use getters and setters for controlled property access

  • Use inheritance only when logically necessary

  • Encapsulate methods that operate on instance data within the class

Real-World Applications

  • Creating models for users, students, products, or courses

  • Organizing code in object-oriented applications

  • Encapsulating state and behavior in frontend frameworks like React or Angular

  • Building reusable components and libraries

  • Implementing inheritance for extending functionalities

Practical Examples

Example 1: Basic Class

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

    greet() {
        console.log("Hello, my name is " + this.name);
    }
}

const student = new Student("Aarushi", 20);
student.greet();

Example 2: Using Getters and Setters

class Student {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }

    get name() {
        return this._name;
    }

    set age(value) {
        if (value > 0) {
            this._age = value;
        }
    }
}

const student = new Student("Priya", 22);
student.age = 23;
console.log(student._age);

Example 3: Inheritance

class Person {
    constructor(name) {
        this.name = name;
    }
}

class Teacher extends Person {
    constructor(name, subject) {
        super(name);
        this.subject = subject;
    }

    teach() {
        console.log(this.name + " teaches " + this.subject);
    }
}

const teacher = new Teacher("Saanvi", "Math");
teacher.teach();
teacher.greet = function() { console.log("Hello from teacher"); };
teacher.greet();

Summary of JavaScript Class Intro

JavaScript classes provide a structured way to define objects, encapsulate data, and implement object-oriented programming concepts. They allow the creation of multiple objects with shared properties and methods, support inheritance, and offer features like getters, setters, and static methods. Proper use of classes improves code readability, maintainability, and scalability, making them essential for modern JavaScript development.


Practice Questions

  1. Basic Class Creation
    Create a class Person with properties firstName and lastName. Add a method fullName() to return the full name. Instantiate an object and log the full name.

  2. Constructor with Multiple Properties
    Create a class Student with firstName, lastName, and grade. Create two instances and log their properties.

  3. Getters and Setters
    Add a getter and setter for grade in the Student class to validate the grade is between 0 and 100. Test with valid and invalid values.

  4. Static Method
    Create a class Calculator with a static method multiply(a, b). Call it directly from the class and verify it cannot be called on an instance.

  5. Instance Method vs Static Method
    Create a class Car with an instance method info() and a static method compare(). Instantiate objects and test both methods.

  6. Inheritance
    Create a class Animal with a method speak(). Extend it with a class Cat that overrides speak() to print a custom message.

  7. Using super()
    In a child class, call the parent constructor using super() and verify that inherited properties are correctly initialized.

  8. Private Fields
    Create a class BankAccount with a private field #balance. Add methods to deposit money and check balance. Attempt to access #balance directly.

  9. Multiple Instances Sharing Methods
    Show that two instances of a class share the same method reference by comparing the function references.

  10. Computed Method Names
    Define a method in a class using a computed property name (e.g., [methodName]()) and call it on an instance to demonstrate dynamic method definition.


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top