Course contentsShow
← JavaScript
Lesson 1827 of 2,72338. Object-Oriented PatternsFree lesson

What Encapsulation Means in JavaScript

Understanding data hiding and access control as a design principle in loosely-typed JavaScript.

What Encapsulation Means in JavaScript

You'll learn: What encapsulation is in JavaScript and how it helps you control access to an object's internal state.


The Core Idea

Encapsulation is the practice of bundling data (properties) and behavior (methods) together while controlling what the outside world can see and modify. In traditional object-oriented programming, you'd use keywords like private and public. JavaScript doesn't enforce access restrictions automatically — it's a loosely-typed language with no built-in "hard" privacy — so encapsulation becomes more of a design principle than a language rule.

The goal? Hide implementation details and expose only what's necessary. This prevents accidental misuse, makes refactoring safer, and creates clearer boundaries between different parts of your code.

How JavaScript Approaches Encapsulation

Since JavaScript won't stop you from accessing any property (everything is technically "public"), you achieve encapsulation through:

  1. Convention: Prefixing properties with _ to signal "don't touch this directly"
  2. Closures: Keeping variables inside factory functions so they're truly inaccessible
  3. Private fields (modern): Using # syntax in classes (ES2022)
  4. Controlled interfaces: Only exposing specific methods/getters/setters
// Factory with closure-based encapsulation
function createBankAccount(initialBalance) {
  let balance = initialBalance; // truly private

  return {
    deposit(amount) {
      balance += amount;
    },
    getBalance() {
      return balance;
    }
  };
}

const account = createBankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.balance); // undefined — can't access directly!

The outside world interacts through deposit() and getBalance(), but balance itself remains hidden. You control how it changes.


Key Takeaway: Encapsulation in JavaScript means hiding internal state and exposing controlled access points, achieved through closures, conventions, or private fields — protecting your data while keeping interfaces clean.