100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
JavaScript

Encapsulation in JavaScript

How JavaScript hides internal object state using ES2022 private class fields (`#field`) and the older underscore naming convention.

OOP in JavaScriptIntermediate8 min readJul 8, 2026
Analogies

1. Introduction

Encapsulation is the object-oriented principle of bundling data with the methods that operate on it, while restricting direct outside access to some of that data. In JavaScript, encapsulation is achieved through private class fields (#field, standardized in ES2022), closures, or — historically — through a naming convention using a leading underscore. Encapsulation protects an object's internal invariants, such as preventing a bank account balance from being set to an invalid value directly.

🏏

Cricket analogy: A team's dressing room bundles player fitness data with the physio who manages it, restricting outside media from directly editing a player's injury status, just as encapsulation bundles data with methods while restricting direct outside access.

2. Syntax

javascript
class ClassName {
  #privateField;          // true private field (ES2022)
  _conventionalField;     // "private by convention" only

  constructor(value) {
    this.#privateField = value;
  }

  #privateMethod() {       // private methods are also supported
    return this.#privateField;
  }

  publicMethod() {
    return this.#privateMethod();
  }
}

3. Explanation

Fields prefixed with # are true private fields, enforced by the JavaScript engine itself, not just by convention. They are only accessible from inside the class body that declares them — even subclasses cannot access a parent's #field directly. Attempting to reference obj.#field from outside the class is a SyntaxError at parse time, not a runtime error, because the engine statically restricts # syntax to class bodies where the field is declared.

🏏

Cricket analogy: A #injuryStatus private field on a Player class is only readable from inside that class, even a subclass like FastBowler can't reach a parent's #field directly — trying player.#injuryStatus from outside is a parse-time SyntaxError, not a runtime crash.

Before ES2022, developers relied on the underscore convention (this._balance) to signal 'please treat this as private,' but it provided no actual enforcement — _balance remained a perfectly ordinary, publicly accessible and enumerable property. True private fields are also excluded from Object.keys(), JSON.stringify(), and for...in loops, whereas underscore-prefixed properties are not.

🏏

Cricket analogy: Before ES2022, a coach might name a field _reservePlayer to signal 'internal use only,' but any reporter could still read or overwrite it freely; true # fields are also hidden from Object.keys() and JSON.stringify(), unlike underscore fields.

Private fields (#field) do not show up in JSON.stringify() output or Object.keys(), because they are not real enumerable properties on the object — they're a special internal slot only accessible from within the declaring class. This makes them ideal for state you never want serialized or leaked.

4. Example

javascript
class BankAccount {
  #balance;

  constructor(owner, balance = 0) {
    this.owner = owner;
    this.#balance = balance;
  }

  deposit(amount) {
    if (amount <= 0) throw new Error("Invalid amount");
    this.#balance += amount;
    return this.#balance;
  }

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

const acc = new BankAccount("Asha", 100);
console.log(acc.deposit(50));
console.log(acc.getBalance());
console.log(acc.owner);
console.log(JSON.stringify(acc));
console.log(Object.keys(acc));
console.log(typeof acc.balance);

5. Output

text
150
150
Asha
{"owner":"Asha"}
[ 'owner' ]
undefined

6. Key Takeaways

  • #field syntax (ES2022) creates true private fields, enforced by the engine, accessible only inside the declaring class.
  • The old underscore convention (_field) is a naming hint only — it provides no real access restriction.
  • Accessing obj.#field from outside the class body is a SyntaxError, not merely a runtime failure.
  • Private fields are excluded from JSON.stringify(), Object.keys(), and for...in enumeration.
  • Private methods (#method()) work the same way, hiding internal implementation details from external code.

Practice what you learned

Was this page helpful?

Topics covered

#JavaScript#JavaScriptProgrammingStudyNotes#Programming#EncapsulationInJavaScript#Encapsulation#Syntax#Explanation#Example#OOP#StudyNotes#SkillVeris