Edit Template
Edit Template

Abstraction

Abstraction is like using a smartphone: you can tap, swipe, and call—but you don’t need to know how the internal circuits work. In programming, abstraction is the same idea: you hide the complex inner workings and only expose what’s necessary.

In JavaScript, while we don’t have official “abstract classes” like in some other languages, we can still create abstraction manually using function constructors and prototypes.

Why Use Abstraction?

Abstraction helps:

  • Hide internal logic that other parts of the code don’t need to know about.

  • Focus on what an object does, not how it does it.

  • Enforce consistency when other developers extend your code.

Simulating Abstract Classes in JavaScript

JavaScript doesn’t have a built-in abstract keyword. But we can simulate abstraction using base classes that throw errors if someone tries to instantiate or use them directly.

				
					function Shape() {
  if (new.target === Shape) {
    throw new Error("Shape is abstract and cannot be instantiated.");
  }
}

Shape.prototype.draw = function () {
  throw new Error("draw() must be implemented by a subclass.");
};

				
			

Now let’s create a subclass that uses this base class:

				
					function Rectangle() {
  Shape.call(this);
}

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

Rectangle.prototype.draw = function () {
  console.log("Drawing a rectangle.");
};

				
			

Using it:

				
					const r = new Rectangle();
r.draw(); // Drawing a rectangle

const s = new Shape(); // ❌ Error: Shape is abstract and cannot be instantiated.

				
			

In this setup:

  • The base class Shape defines a method draw() but does not implement it.

  • The subclass Rectangle is required to implement draw() to work properly.

This is a simple, effective abstraction technique in vanilla JavaScript.

A Note on Interfaces

JavaScript doesn’t have interfaces like TypeScript or Java. But if you want to ensure certain methods exist on a class, you can do a manual check:

				
					function validateShape(obj) {
  if (typeof obj.draw !== "function") {
    throw new Error("Object must implement a draw() method.");
  }
}

				
			

You can call this check before using the object to ensure it meets your expected structure.

Final Thoughts

Abstraction keeps your code clean and easy to manage. It’s like organizing your workspace—users don’t need to see the wires under the desk, just the clean surface where they get things done.

In JavaScript, even without native abstract classes, you can still achieve powerful abstraction using prototypes and conventions. This is especially helpful when working with teams or building code that others will extend later.

Scroll to Top