Abstraction

Abstraction in JavaScript refers to the concept of hiding complex implementation details and showing only the essential features of an object or function.

It allows developers to work with high-level ideas rather than dealing with low-level implementation complexities.

// Define a Car object
function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
    
    // Method to start the car
    this.start = function() {
        console.log("Engine started");
    };

    // Method to stop the car
    this.stop = function() {
        console.log("Engine stopped");
    };
}

// Create a new Car instance
var myCar = new Car("Toyota", "Camry", 2022);

// Accessing properties directly
console.log(myCar.make); // Output: Toyota

// Calling methods
myCar.start(); // Output: Engine started
myCar.stop();  // Output: Engine stopped

In this example, Car is an abstraction. It abstracts away the internal details of what makes a car work and provides a simple interface (properties and methods) to interact with it.

As a user of the Car object, you don't need to know how the engine starts or stops internally;

you simply call start() or stop() methods, abstracting away the complexities of the underlying implementation.

Abstraction allows us to think about a car in terms of what it does (start, stop) and what properties it has (make, model, year), without worrying about how those actions are implemented under the hood.

This separation of concerns makes our code more manageable, modular, and easier to maintain.

Last updated