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
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
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
150
150
Asha
{"owner":"Asha"}
[ 'owner' ]
undefined6. Key Takeaways
#fieldsyntax (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.#fieldfrom outside the class body is a SyntaxError, not merely a runtime failure. - Private fields are excluded from
JSON.stringify(),Object.keys(), andfor...inenumeration. - Private methods (
#method()) work the same way, hiding internal implementation details from external code.
Practice what you learned
1. What distinguishes a `#balance` private field from a `_balance` conventionally-named field?
2. What kind of error occurs when code outside the class tries to write `obj.#balance`?
3. Does `JSON.stringify()` include `#`-prefixed private fields in its output?
4. Can a subclass directly access a `#field` declared in its parent class?
5. In the BankAccount example, why does `acc.deposit(50)` followed by `acc.getBalance()` both print 150?
Was this page helpful?
You May Also Like
Classes in JavaScript
How ES6 class syntax provides a cleaner, structured way to create objects and implement object-oriented patterns on top of JavaScript's prototype system.
Getters and Setters in JavaScript
How the `get` and `set` keywords define accessor properties that run code on read/write while still looking like plain property access to callers.
Closures in JavaScript
Understand how closures let inner functions remember and access variables from their outer scope, and how loop variable capture can trip you up.
Objects in JavaScript
Learn how to create, access, and modify JavaScript objects, and understand why objects behave as reference types.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics