Abstraction in JavaScript (original) (raw)

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.

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());

``

Output

Anuj is 30 years old.

**In this example

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: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow></mrow><annotation encoding="application/x-tex"></annotation></semantics></math></span><span class="katex-html" aria-hidden="true"></span></span>{amount}); } getB() { return this.#balance; } }

const a1 = new B(1000); a1.deposit(500); console.log(a1.getB());

``

Output

Deposited: $500 1500

Use Cases of Abstraction

Benefits of Abstraction in JavaScript