What is Abstraction in JavaScript?
In JavaScript, abstraction signifies the practice of concealing intricate details while highlighting only the fundamental attributes or functionalities of an object. In essence, it aids in minimizing complexity, enabling us to create and implement sophisticated software systems more effectively. Abstraction can be accomplished through the use of abstract classes or by utilizing interfaces.
Abstraction refers to the method of concealing the underlying implementation specifics while presenting solely the functionalities to the end-users. To put it differently, it disregards unnecessary details and highlights only the essential information.
Points to Remember
- We cannot create an instance of Abstract Class.
- It reduces the duplication of code.
Why do we use Abstraction in JavaScript?
In JavaScript, abstraction serves multiple significant functions. These include:
Simplification
By employing abstraction, programmers have the ability to streamline intricate systems by concealing superfluous details and revealing only the crucial components. This approach enhances the clarity and maintainability of the code.
Encapsulation
By employing abstraction, we can conceal the implementation specifics of a certain function, enabling developers to concentrate on utilizing its functionality instead of the intricacies of its implementation. This approach fosters modularity and diminishes the interdependencies among various components of the codebase.
Reusability
By distilling shared patterns and features into reusable components, developers can conserve both time and effort. This approach allows them to utilize existing code rather than rewriting it from scratch for every instance.
Flexibility
Through the use of abstraction, programmers have the ability to design an interface that can be executed in various ways internally. This approach offers the advantage of flexibility, allowing for simpler adjustments to evolving requirements and environments without necessitating extensive alterations to a significant part of the application.
Maintainability
By concealing implementation specifics, we can decrease the chances of encountering bugs, allowing modifications or enhancements to be made to the program without impacting other components of the system.
In JavaScript, abstraction can be accomplished through various means, including functions, classes, modules, and libraries, among others. Utilizing these resources allows developers to arrange and structure their code or applications in a manner that enhances clarity, maintainability, and scalability.
How we can achieve abstraction in JavaScript?
In JavaScript, it is possible to establish an abstraction by structuring your code in such a manner that the intricate details are concealed while only the fundamental features are made accessible to different sections of the applications.
To implement abstraction in JavaScript, it is necessary to construct an abstract class along with an interface, despite the fact that JavaScript does not provide built-in support for such concepts. A majority of developers typically rely on prototypes, functions, and object-oriented design patterns to enforce the principles of abstraction.
Example 1:
// Define a function called `add` that takes two arguments, `a` and `b`, and returns their sum.
function add(a, b) {
return a + b;
}
// Define a function called `subtract` that takes two arguments, `a` and `b`, and returns their difference.
function subtract(a, b) {
return a - b;
}
// Define a function called `multiply` that takes two arguments, `a` and `b`, and returns their product.
function multiply(a, b) {
return a * b;
}
// Define a function called `divide` that takes two arguments, `a` and `b`, and returns their quotient.
function divide(a, b) {
return a / b;
}
// Define a function called `calculate` that takes two arguments, `a` and `b`, and an operator, and returns the result of applying the operator to `a` and `b`.
function calculate(a, b, operator) {
switch (operator) {
case 'add':
return add(a, b);
case 'subtract':
return subtract(a, b);
case 'multiply':
return multiply(a, b);
case 'divide':
return divide(a, b);
default:
throw new Error('Invalid operator');
}
}
// Call the `calculate` function with the arguments 5, 3, and 'add'.
const result = calculate(5, 3, 'add');
// Print the result to the console.
console.log(result); // Output: 8
Output:
Example 2:
Let’s implement a program to determine whether it is possible to instantiate an Abstract class.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//creating a constructor function
function vehicle()
{
this.vehicleName = vehicleName;
throw new Error("you cannot create an instance of Abstract class");
}
Vehicle.prototype.display= function()
{
return this.vehicleName;
}
var vehicle = new Vehicle();
</script>
</body>
</html>
Output:
Example 3
Let's take an example to achieve abstraction
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//creating a constructor function
function Vehicle()
{
this.vehicleName = "vehicleName";
throw new Error("You cannot create an instance of Abstract Class");
}
Vehicle.prototype.display= function()
{
return "Vehicle is:" +this.vehicleName;
}
//creating a constructor function
function Bike(vehicleName)
{
this.vehicleName = vehicleName;
}
//Creating object without using the function constructor
Bike.prototype = Object.create(Vehicle.prototype);
var bike= new Bike(" Hero Honda");
document.writeln(bike.display());
</script>
</body>
</html>
Output:
Example 4:
// Define a function called `calculateArea` that takes an object with a `width` and `height` property, and returns the area of the rectangle.
function calculateArea(rectangle) {
return rectangle.width * rectangle.height;
}
// Define an object called `rectangle1` with a `width` of 5 and a `height` of 10.
const rectangle1 = {
width: 3,
height: 10
};
// Define an object called `rectangle2` with a `width` of 10 and a `height` of 20.
const rectangle2 = {
width: 10,
height: 20
};
// Call the `calculateArea` function with the `rectangle1` object as an argument.
const area1 = calculateArea(rectangle1);
// Call the `calculateArea` function with the `rectangle2` object as an argument.
const area2 = calculateArea(rectangle2);
// Print the areas to the console.
console.log(`Area of rectangle1: ${area1}`);
console.log(`Area of rectangle2: ${area2}`);
Output:
Area of rectangle1: 30
Area of rectangle2: 200