Flat Preloader Icon

JS Abstraction

Abstraction is a fundamental concept in programming that involves hiding the complex implementation details of a system and exposing only the necessary functionality or interface to the outside world. It allows developers to focus on what an object does rather than how it does it, promoting simplicity, modularity, and code reusability. In JavaScript, abstraction is often achieved through the use of classes, methods, and access modifiers.

Key Concepts:

  • Classes:

    • Classes are blueprints for creating objects with specific properties and behaviors. They encapsulate data (properties) and functionality (methods) related to a specific entity.
  • Methods:

    • Methods are functions defined within classes that define the behavior of their instances. They allow objects to perform actions and interact with their internal state.
  • Access Modifiers:

    • Access modifiers control the access to the properties and methods of a class. In JavaScript, access modifiers are not explicitly defined, but conventionally, properties and methods prefixed with an underscore (_) are considered private and not intended for direct external access.
				
					class Vehicle {
    constructor(make, model) {
        this._make = make; 
        // Encapsulated property
        this._model = model; 
        // Encapsulated property
    }

    // Encapsulated method
    displayInfo() {
        console.log(`Make: 
        ${this._make}, Model: ${this._model}`);
    }
}

// Creating an instance of the Vehicle class
let car = new Vehicle("Toyota", "Camry");

// Accessing encapsulated method
car.displayInfo();
// Output: Make: Toyota, Model: Camry

// Accessing encapsulated properties 
(not recommended)
console.log(car._make); 
// Output: Toyota

				
			

Benefits of Abstraction:

  • Simplicity:

    • Abstraction hides unnecessary details and complexities, making the code easier to understand and maintain.
  • Modularity:

    • Abstraction promotes modularity by organizing related functionality into cohesive units (classes). This improves code organization, readability, and maintainability.
  • Code Reusability:

    • Abstraction allows for the creation of reusable components with well-defined interfaces, reducing code duplication and promoting code reusability.

Limitations:

  • JavaScript does not have built-in access modifiers like other OOP languages (e.g., Java, C#). Abstraction relies on naming conventions and coding conventions to achieve data hiding and encapsulation.