Classes (ES6)

Program demonstrating ES6 classes

IntermediateTopic: Object Programs
Back

JavaScript Classes (ES6) Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Class declaration
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    greet() {
        return `Hello, I'm ${this.name}`;
    }
    
    getAge() {
        return this.age;
    }
}

let person1 = new Person("Alice", 25);
console.log(person1.greet());
console.log("Age:", person1.getAge());

// Class with inheritance
class Student extends Person {
    constructor(name, age, grade) {
        super(name, age);  // Call parent constructor
        this.grade = grade;
    }
    
    study() {
        return `${this.name} is studying`;
    }
    
    // Override parent method
    greet() {
        return `Hi, I'm ${this.name}, a student`;
    }
}

let student1 = new Student("Bob", 20, "A");
console.log("\nStudent:");
console.log(student1.greet());
console.log(student1.study());
console.log("Grade:", student1.grade);

// Static methods
class MathUtils {
    static add(a, b) {
        return a + b;
    }
    
    static multiply(a, b) {
        return a * b;
    }
}

console.log("\nStatic methods:");
console.log("Add:", MathUtils.add(5, 3));
console.log("Multiply:", MathUtils.multiply(5, 3));

// Getters and Setters
class Circle {
    constructor(radius) {
        this._radius = radius;
    }
    
    get radius() {
        return this._radius;
    }
    
    set radius(value) {
        if (value > 0) {
            this._radius = value;
        } else {
            throw new Error("Radius must be positive");
        }
    }
    
    get area() {
        return Math.PI * this._radius ** 2;
    }
}

let circle = new Circle(5);
console.log("\nCircle:");
console.log("Radius:", circle.radius);
console.log("Area:", circle.area.toFixed(2));
circle.radius = 10;
console.log("New radius:", circle.radius);
console.log("New area:", circle.area.toFixed(2));
Output
Hello, I'm Alice
Age: 25

Student:
Hi, I'm Bob, a student
Bob is studying
Grade: A

Static methods:
Add: 8
Multiply: 15

Circle:
Radius: 5
Area: 78.54
New radius: 10
New area: 314.16

Understanding Classes (ES6)

This program demonstrates ES6 classes in JavaScript.

Class Declaration

Modern syntax for object-oriented programming:

class ClassName {
    constructor(parameters) {
    }
    
    method() {

        // Method
    }
}
        // Initialize

Constructor

Special method called when object is created:

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

Inheritance

Extend parent class:

class Child extends Parent {
    constructor(params) {
        super(params);  // Call parent constructor
    }
}

super keyword:

Calls parent constructor
Accesses parent methods
Required in child constructor

Method Overriding

Child can override parent methods:

class Child extends Parent {
    method() {
    }
}
        // Override parent method

Static Methods

Belong to class, not instance:

class Utils {
    static method() {
    }
}
Utils.method();  // Not instance.method()
        // Called on class, not instance

Getters and Setters

Control property access:

get property() {
}

set property(value) {

    // Validation
    this._property = value;
}
    return this._property;

Benefits:

Validation
Computed properties
Encapsulation

Class vs Constructor Function:

| Feature | Class | Constructor |

|---------|-------|-------------|

| Syntax | Modern | Traditional |

| Hoisting | No | Yes |

| Strict mode | Always | Optional |

| Inheritance | extends | Manual |

When to Use:

-

Class

: Modern OOP, inheritance

-

Constructor

: Legacy code, simple objects

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Classes (ES6)

This JavaScript program is part of the "Object Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents