Abstraction in JavaScript
Last Updated :
08 Feb, 2025
In JavaScript, Abstraction can be defined as the concept of hiding the inner complex workings of an object and exposing only the essential features to the user.
- Hiding Complexity: Implementation is hidden, it shows only the necessary details.
- Modularity: Code is organized in a reusable form, which improves maintainability and readability.
- Security: Important data cannot be directly accessed, they are hidden.
- Reusability: The code can be reused across different applications.
In JavaScript, abstraction is often achieved through functions, classes, and modules that encapsulate behaviour and expose only the necessary parts to the outside world.
JavaScript
class P{
constructor(name, age) {
this.name = name;
this.age = age;
}
getD() {
return `${this.name} is ${this.age} years old.`;
}
}
const p1 = new P("Anuj", 30);
console.log(p1.getD());
OutputAnuj is 30 years old.
In this example
- The class P encapsulates both data (name, age) and behaviour (getD method).
- The getD() method provides a simple, reusable way to retrieve a formatted description.
- Creating an instance (p1) and calling getD() is straightforward, with the underlying logic hidden.
- You can create multiple instances of P, each maintaining its own data while reusing the same logic.
Implementing Abstraction in JavaScript
The JavaScript does not provide built-in support for implementing the abstraction like the other programming language gives. However we can implement abstraction in JavaScript using functions, objects, closures, and classes.
Using Functions
Functions are one of the most simple ways to introduce abstraction in JavaScript. They allow you to wrap complex logic into a reusable block of code, exposing only the function name and parameters.
JavaScript
function a(radius) {
return Math.PI * radius * radius;
}
console.log(a(5));
Using Objects and Methods
Classes and objects provide a more structured way to achieve abstraction by bundling related properties and methods into a single unit.
JavaScript
const car = {
brand: "Toyota",
start: function() {
console.log("Car started");
}
};
car.start();
Using Closures
Closures help in abstraction by restricting access to certain variables, making them private.
JavaScript
function Count() {
let c1 = 0;
return {
inc: function() {
c1++;
console.log(c1);
}
};
}
const c2 = Count();
c2.inc();
c2.inc();
Using Classes and Encapsulation
ES6 classes help implement abstraction by using constructor functions and private fields (using closures or symbols).
JavaScript
class B{
#balance;
constructor(B1) {
this.#balance = B1;
}
deposit(amount) {
this.#balance += amount;
console.log(`Deposited: $${amount}`);
}
getB() {
return this.#balance;
}
}
const a1 = new B(1000);
a1.deposit(500);
console.log(a1.getB());
OutputDeposited: $500
1500
Use Cases of Abstraction
- API Development: Abstraction can be used to create the APIs where the only necessary functionality is exposed and internal logic is hidden.
- Database Operations: Database interactions are abstracted using Object-Relational Mapping (ORM) frameworks, so developers work with high-level models instead of raw SQL queries.
- Middleware in Web Servers: Web servers use middleware functions to abstract authentication, logging, and error handling.
- Security and Encryption: Sensitive operations like password hashing and encryption are abstracted into reusable functions, preventing direct manipulation of security mechanisms.
Benefits of Abstraction in JavaScript
- Better Code Quality: Your code will be simpler and easier to read.
- No Repeated Code: You’ll store shared logic in one place instead of copying it everywhere.
- Easier Updates: Changing one piece of logic won’t break other parts of the application.
- Team-Friendly: Developers can work on different parts without needing to know every detail of the codebase.
Similar Reads
Encapsulation in JavaScript Encapsulation is a fundamental concept in object-oriented programming that refers to the practice of hiding the internal details of an object and exposing only the necessary information to the outside world. Encapsulation can be achieved using two techniques: Table of Content Using ClosuresUsing Cla
3 min read
Interesting Facts About JavaScript JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Interesting Facts A
5 min read
Introduction to JavaScript JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at
7 min read
JavaScript Function Examples A function in JavaScript is a set of statements that perform a specific task. It takes inputs, and performs computation, and produces output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different
3 min read
JavaScript Basics JavaScript is a versatile, lightweight scripting language widely used in web development. It can be utilized for both client-side and server-side development, making it essential for modern web applications. Known as the scripting language for web pages, JavaScript supports variables, data types, op
6 min read
Interesting Facts about JavaScript Functions Let us talk about some interesting facts about JavaScript Functions that can make you an efficient programmer.Functions Are First-Class CitizensJavaScript treats functions as first-class citizens, meaning they can be:Stored in variablesPassed as arguments to other functionsReturned from other functi
3 min read
Introduction to Javascript Engines JavaScript is a scripting language and is not directly understood by computer but the browsers have inbuilt JavaScript engine which help them to understand and interpret JavaScript codes. These engines help to convert our JavaScript program into computer-understandable language. A JavaScript engine
4 min read
Typescript Abstract Class TypeScript, a superset of JavaScript, introduces many features to improve code organization, readability, and maintainability. One of these features is abstract classes. This article will explain what abstract classes are, how they work, and how to use them effectively in your TypeScript projects.Th
3 min read
JavaScript Inheritance Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class or object to derive properties and behaviours from another. In JavaScript, inheritance is like a parent-child relationship, where objects, functions, or classes can inherit properties and methods from oth
6 min read