Skip to content
AgileLogics
5 min read

Encapsulation with Closures

Prerequisites: Functions, Classes and objects

Encapsulation means keeping an object's internal details private, and only exposing a deliberate, controlled way to interact with it. JavaScript classes support real private fields with a # prefix:

class BankAccount {
    #balance;

    constructor(balance) {
        this.#balance = balance;
    }

    deposit(amount) {
        if (amount <= 0) {
            throw new Error("Deposit must be positive");
        }
        this.#balance += amount;
    }

    getBalance() {
        return this.#balance;
    }
}

Code outside the class calls account.deposit(50) — it cannot access account.#balance directly (unlike the leading-underscore convention in some other languages, # fields are genuinely enforced by JavaScript, not just a naming hint).