JavaScript ES6 Classes

1. What are Classes?

Classes are templates for creating objects. They encapsulate data (properties) and behavior (methods) in one structure.

2. Class Syntax

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

    greet() {
        document.write(`Hello, my name is ${this.name}`);
    }
}

let person1 = new Person("Ragini", 25);
person1.greet();
        
Output will appear here...

3. Inheritance

class Student extends Person {
    constructor(name, age, grade) {
        super(name, age);
        this.grade = grade;
    }

    study() {
        document.write(`${this.name} is studying in grade ${this.grade}`);
    }
}

let student1 = new Student("Ragini", 25, "12th");
student1.greet();
student1.study();
        
Output will appear here...

4. Example: Class Usage

class Car {
    constructor(brand, model) {
        this.brand = brand;
        this.model = model;
    }

    info() {
        return `${this.brand} - ${this.model}`;
    }
}

let car1 = new Car("Tesla", "Model 3");
document.write(car1.info());
            
Output will appear here...

Comparison Table: Classes vs Functions

Feature Class Function Constructor
Syntax class Person { } function Person() { }
Inheritance extends + super prototype
Readability Modern Old style
✅ Best Practice: Use ES6 classes for modern OOP JavaScript.

Practice Questions

Test your understanding of JavaScript Classes.

Easy

Q1: Define a basic class.

  • Define a class named Rectangle.
  • Add a constructor method that takes width and height as parameters.
  • Inside the constructor, assign the parameters to this.width and this.height.
Easy

Q2: Create a class instance.

  • Assume the Rectangle class from the previous question is defined.
  • Create a new instance (object) of the Rectangle class with a width of 10 and a height of 5.
  • Store it in a variable named myRect and log its width property.
Medium

Q3: Add a method to a class.

  • Inside the Rectangle class, add a method named getArea().
  • The method should calculate and return the area (width * height).
  • Create an instance of the class and log the result of getArea() to the console.
Medium

Q4: Implement class inheritance.

  • Create a new class named Square that inherits from the Rectangle class.
  • Add a constructor to Square that accepts a single parameter side.
  • Use the super() keyword to pass side as both the width and height to the parent constructor.
Hard

Q5: Create and call a static method.

  • Write a class named MathUtil.
  • Inside it, define a static method named add that takes two parameters (a, b) and returns their sum.
  • Call this method directly on the class (without creating an instance) and log the result.

Answer

Code: