Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 156 ยท Classes and Objects in Depth

OOP Principles in JavaScript

Apply encapsulation, abstraction, inheritance, polymorphism and the SOLID principles in JavaScript, and learn when plain functions beat classes.

The previous lessons taught the mechanics of objects in JavaScript: prototypes, classes, inheritance, private and static members and composition. This lesson is about design: the ideas that decide whether a codebase full of objects stays easy to change or turns into a tangle.

Object-oriented programming is usually summed up in four principles (encapsulation, abstraction, inheritance and polymorphism) plus five design guidelines known as SOLID. Most of them were described for languages like Java and C#, where everything must live in a class. JavaScript is more relaxed: it has classes, but also closures, plain objects and first-class functions. So for each principle you'll see the idea, how it looks in idiomatic JavaScript, and where the JavaScript way differs from the textbook one.

Encapsulation: protect the object's rules

Encapsulation means an object keeps its data and the code that changes that data together, and hides the data from the outside. The point isn't secrecy. It's that the object can guarantee its own rules (its invariants). A bank account must never go below zero; a date range must never end before it starts. If any code anywhere can write to the fields directly, nobody can guarantee anything.

JavaScript offers two solid ways to hide state: #private class fields and closures.

JS Two ways to encapsulate state

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the second half of encapsulation: the history getter returns a copy. Returning the real array would let callers change the object's insides without going through its methods, a leak that # alone can't stop.

Convention vs enforcement. Older code marks "private" members with an underscore, like this._balance. That is only a polite request; anyone can still read and write it. #private fields (in every modern browser since 2021) and closures are real privacy. A WeakMap keyed by the object is a third, older technique you may meet in libraries.

Abstraction: hide the how, show the what

Abstraction is encapsulation's partner. Encapsulation hides data; abstraction hides complexity. A good object offers a small set of operations that say what it does, and keeps how it does it private. You call cart.total() without caring whether it caches, rounds or applies tax rules in three steps.

JavaScript has no abstract keyword and no interface keyword (TypeScript adds both). You express abstraction in two ways:

  • An agreed shape. Document the methods an object must have and let any object that has them be used. This is the most common approach.
  • A base class that refuses to be used directly. Check new.target in the constructor and throw for missing methods. This gives a clear error early instead of a confusing one later.
JS An abstract base class in plain JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The caller only needs export(rows). Filtering inactive rows lives in one place, and each subclass fills in the one step that differs. This shape, a fixed algorithm with a replaceable step, is called the template method pattern.

Inheritance vs composition

Inheritance lets a class reuse and specialize another class (class CsvExporter extends Exporter). It's the right tool for a genuine, stable is-a relationship, like the exporters above or custom error types. It's also the tightest coupling two pieces of code can have: a subclass depends on its parent's internals, and deep hierarchies break when requirements cut across them.

Composition builds objects from parts they have and passes behavior in as values. The Composition lesson covers delegation, factory functions and mixins in depth. As a rule of thumb:

  • Use inheritance when the subclass truly is a kind of the parent, the hierarchy is shallow (one or two levels), and the parent was designed to be extended.
  • Use composition in every other case, and whenever you're unsure. It's easy to turn composition into inheritance later; the reverse is painful.

Polymorphism: one call, many behaviors

Polymorphism ("many shapes") means code can work with different kinds of objects through the same interface, and each object responds in its own way. The code that calls shape.area() doesn't know or care which shape it has.

JavaScript gives you polymorphism in two flavors:

  • Method overriding: subclasses replace a parent method, and the right version is found through the prototype chain at call time.
  • Duck typing: "if it walks like a duck and quacks like a duck, it's a duck". Any object with the right method works, related by inheritance or not. This is the dominant style in JavaScript.
JS Overriding and duck typing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The loop never asks "are you a Circle?". Code full of if (x instanceof A) โ€ฆ else if (x instanceof B) โ€ฆ is usually a sign that polymorphism is missing: move the varying behavior into a method each type implements. The built-in protocols (Symbol.iterator, toString, toJSON, then for promises) show how deeply JavaScript relies on duck typing. You'll meet more of them in Iterators and Generators.

Relationships between objects: association, aggregation, composition

Objects rarely live alone. Besides is-a (inheritance), designers describe has-a relationships, and they distinguish three strengths by asking "who owns whom, and who controls the lifetime?":

  • Association: one object uses or knows about another, and neither owns the other. A lesson refers to a teacher and some students; the teacher exists independently and can appear in many lessons.
  • Aggregation: a weak whole-part relationship. The whole holds its parts, but the parts can exist without it and may be shared. A Team has players, but if the team disbands the players still exist, and one player can be in two teams.
  • Composition: a strong whole-part relationship. The whole creates and owns its parts, and they make no sense without it. A Car creates its own Engine and never hands it out.

JavaScript has no keywords for these; the difference lies in who creates the part and who can reach it. If the part is passed in from outside, it is association or aggregation. If the whole creates it internally (often in a #private field), it is composition.

JS Association, aggregation and composition

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is the same idea as the composition lesson, seen from the modeling side. When you are unsure which one you have, ask: "if I delete the whole, should the part disappear too?" Yes means composition; no means aggregation or association.

Access levels: public, protected and private

Many languages have public, protected and private keywords. JavaScript has real public and private (the # syntax), and leaves protected to convention:

Level JavaScript technique Enforced?
Public ordinary property or method n/a
"Protected" (for subclasses) a leading underscore, _sound(), or a documented naming rule no, convention only
Private to the class #field and #method() yes, by the language
Private to a function a variable captured in a closure yes, nothing else can reach it
Private to a file a variable or function you simply do not export from the module yes
JS Access levels in practice

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Prefer #private for anything that must not be touched, since it cannot be bypassed (or even detected) from outside. Use the underscore only to mark an extension point or old code, and remember that tooling does not enforce it. Symbols (see BigInt and Symbol) hide keys from casual enumeration but are not private.

Kinds of inheritance and polymorphism

You will meet these textbook names in interviews. Here is how each maps onto JavaScript:

  • Single inheritance: one parent, class B extends A. This is all JavaScript classes allow directly.
  • Multilevel: a chain, C extends B extends A. Keep chains short.
  • Hierarchical: several subclasses share one parent (Circle and Rect extend Shape).
  • Multiple inheritance: not supported. Combine behavior with composition or mixins (functions that add methods to a class), covered in Composition.
  • Runtime (overriding) polymorphism: a subclass replaces a parent method, and the right one runs for each object, as in the shapes above.
  • "Compile-time" polymorphism (overloading): JavaScript has none; one function checks its arguments instead. See Functions.
  • Ad hoc and parametric polymorphism: + working on numbers and strings, and generic functions like Array.prototype.map, which work for any element type. In plain JavaScript this comes for free from dynamic typing; TypeScript adds generics to describe it.

SOLID in JavaScript

SOLID is a set of five guidelines for code that is easy to change. They were written with classes in mind, but each has a natural JavaScript form, often with functions instead of classes.

S: Single responsibility. A unit of code should have one reason to change. A UserService that validates input, writes to the database, sends emails and formats HTML changes whenever any of those concerns does. Split it so each piece has one job; in JavaScript, these pieces are often separate modules of small functions.

O: Open/closed. Code should be open for extension but closed for modification. You should be able to add a new case (a new payment method, a new export format) without editing the code that already works. A lookup table or registry of handlers usually beats a growing switch.

L: Liskov substitution. A subclass must be usable anywhere its parent is expected, without surprises. If Square extends Rectangle but setting its width secretly changes its height, code written for rectangles breaks. If a child can't honor the parent's promises, it shouldn't be a child.

I: Interface segregation. Don't force code to depend on methods it doesn't use. In JavaScript this means small objects and parameters: ask for { send }, not for an entire MailClient with 30 methods. Destructuring in the parameter list documents exactly what you need.

D: Dependency inversion. High-level logic shouldn't depend on low-level details; both should depend on an agreed shape. Pass the database, clock or HTTP client in instead of importing a specific one inside. That's what makes code testable with fakes.

Here are O, I and D working together:

JS Open/closed, small interfaces and injected dependencies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

And here is the classic Liskov violation, so you can see the surprise for yourself:

JS When a subclass breaks its parent's promise

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A square is a rectangle in geometry, but not in code where rectangles promise independent width and height. Inheritance must follow behavior, not real-world categories.

Treat SOLID as questions to ask during a review ("what would I have to edit to add a new X?", "can I test this without a real database?"), not as laws. Applying all five to a 40-line script just adds ceremony.

When not to use classes

Classes are one tool among several. JavaScript lets you skip them whenever they add nothing:

  • Stateless logic is a function. A class with a constructor that stores nothing and one method, like new PriceFormatter().format(x), is just formatPrice(x) with extra steps.
  • A bag of helpers is a module. A class made only of static methods is better as named exports from a module; bundlers can then drop the unused ones.
  • Data is data. Records that come from JSON and go back to JSON are often simplest as plain objects plus functions that work on them. Class instances lose their methods when they go through JSON.stringify/JSON.parse anyway (see JSON).
  • Callbacks need care. Methods passed as callbacks lose their this unless you bind them or use arrow-function fields (see this). Closures don't have this problem.

On the other hand, classes are a great fit for many objects with shared behavior and changing state (game entities, UI widgets, data structures like the ones in Data Structures), for custom errors, and when a platform expects them, such as web components extending HTMLElement. Many good JavaScript codebases mix both: classes for stateful things, functions for transformations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main purpose of encapsulation?

    Hiding state behind methods means the object can enforce invariants, such as a balance that never goes negative.
  2. 2. A getter returns this.#items directly. What is the problem?

    # hides the field name, not the value it points to. Return a copy (or a frozen view) to keep the object in control.
  3. 3. Which is an example of duck typing?

    Duck typing cares only that the object has the needed method, not what class it belongs to.
  4. 4. Adding a new notification channel requires editing a big switch statement inside notify(). Which principle is this breaking?

    The open/closed principle says you should extend behavior (register a new channel) without modifying working code.
  5. 5. Why does Square extends Rectangle with linked width and height violate Liskov substitution?

    A subclass must keep its parent's promises. Rectangle promises independent sides; Square breaks that promise.

Summary

  • Encapsulation keeps data and the code that changes it together; use #private fields or closures, and return copies instead of internal arrays and objects.
  • Abstraction exposes what an object does and hides how; express it with an agreed shape or a base class that checks new.target.
  • Inheritance fits shallow, stable is-a relationships; prefer composition otherwise.
  • Polymorphism lets one call work on many kinds of objects, through method overriding or, more often in JavaScript, duck typing.
  • Association, aggregation and composition describe has-a links of increasing strength; JavaScript expresses them by who creates and can reach the part. Use #private for real privacy and the underscore only as a convention.
  • SOLID: one reason to change, extend without editing, subclasses keep promises, small interfaces, and dependencies passed in.
  • Skip classes for stateless logic, helper collections and plain data; use them for many stateful objects, custom errors and platform base classes.

Next: Errors and try...catch โ€” what happens when things go wrong, and how to handle it.