JavaScript Abstraction

What is Abstraction in JavaScript?

In JavaScript, abstraction refers to the concept of hiding complex details and showing only an object's essential features or functionalities. Simply, it helps us reduce complexity and allows us to design efficiently and implement complex software systems. We can achieve abstraction with either abstract classes or with the help of interfaces An abstraction is a way of hiding the implementation details and showing only the functionality to the users. In other words, it ignores the irrelevant details and shows only the required ones.

Syntax


class AbstractClass {
    constructor() {
        if (new.target === AbstractClass) {
            throw new Error("Cannot instantiate an abstract class.");
        }
    }

    abstractMethod() {
        throw new Error("Abstract method must be implemented in the derived class.");
    }              
}
            
class ConcreteClass extends AbstractClass {
    abstractMethod() {
        return "Abstract method implemented in ConcreteClass.";
    }             
}
            
const instance = new ConcreteClass();
console.log(instance.abstractMethod()); 
                        

Output

Abstract method implemented in ConcreteClass.

Key Features of Abstraction:

Example: Implementing Abstraction

Example:


class Shape {
    constructor() {
        if (new.target === Shape) {
            throw new Error("Cannot instantiate an abstract class.");
        }
    }

    calculateArea() {
        throw new Error("Abstract method must be implemented in the derived class.");
    }             
}
            
class Rectangle extends Shape {
    constructor(width, height) {
        super();
        this.width = width;
        this.height = height;             
    }
            
    calculateArea() {
        return this.width * this.height;
    }
}
            
class Circle extends Shape {
    constructor(radius) {
        super();
        this.radius = radius;
    }
            
    calculateArea() {
        return Math.PI * this.radius ** 2;
    }
}
            
// Using the classes
const shapes = [
    new Rectangle(5, 10),
    new Circle(7)
];
shapes.forEach(shape => console.log(shape.calculateArea()));
           
            

Output

50
153.93804002589985

Explanation of Code:

Advantages of Abstraction:

Why do we use Abstraction in JavaScript?

Abstraction in JavaScript, we have several important purposes to use it. Such as: