MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Private Fields & Methods (#field)0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
2.1Class Syntax & Constructor Methods2.2Getters, Setters & Static Methods2.3Private Fields & Methods (#field)2.4Prototypal Inheritance vs Class Inheritance2.5Mixins & Object Composition
HomeTutorialsJavaScript for AdvancedPrivate Fields & Methods (#field)
Prototypal Inheritance vs Class Inheritance

Private Fields & Methods (#field)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

For over two decades, JavaScript lacked true language-level encapsulation. Developers relied on naming conventions (like _underscorePrefix) or closures to simulate privacy. Introduced officially in ES2022, Private Class Fields and Methods (using the # prefix) provide hard, engine-enforced privacy.


1. The Historical Problem: Soft Conventions vs. Hard Privacy

1// LEGACY: Underscore was merely a gentleman's agreement!
2class LegacyAccount {
3 constructor(pin) {
4 this._pin = pin; // Anyone can still do: account._pin = 0000!
5 }
6}

External consumers could inspect and mutate _pin directly, breaking invariants and leaking secrets.


2. Modern Private Fields Syntax: #field

Private fields are declared at the class body level using the # symbol. Attempting to access them outside the class results in a compile-time SyntaxError:

1class SecureVault {
2 // 1. Private Field Declaration
3 #masterKey;
4 #balance = 0;
5 
6 constructor(owner, initialKey, deposit) {
7 this.owner = owner; // Public property
8 this.#masterKey = initialKey; // Private property
9 this.#balance = deposit; // Private property
10 }
11 
12 // Public method accessing private field internally
13 verifyAndWithdraw(enteredKey, amount) {
14 if (this.#masterKey !== enteredKey) {
15 throw new Error('Access Denied: Invalid Security Key.');
16 }
17 if (amount > this.#balance) {
18 throw new Error('Insufficient Vault Funds.');
19 }
20 this.#balance -= amount;
21 return `Dispensed $${amount}. Remaining: $${this.#balance}`;
22 }
23}
24 
25const vault = new SecureVault('Wayne Enterprises', 'batman99', 500000);
26 
27console.log(vault.owner); // "Wayne Enterprises"
28 
29// ATTEMPTING TO ACCESS PRIVATE FIELD OUTSIDE CLASS:
30// console.log(vault.#masterKey);
31// SYNTAX ERROR: Private field '#masterKey' must be declared in an enclosing class!

3. Private Methods & Accessors

You can make helper methods, getters, and setters private using #:

1class CryptographicKeyManager {
2 #rawSeed;
3 
4 constructor(seed) {
5 this.#rawSeed = seed;
6 }
7 
8 // Private helper method
9 #generateHash(data) {
10 return `hash_${data}_${this.#rawSeed}`;
11 }
12 
13 // Public API
14 signPayload(payload) {
15 return this.#generateHash(payload);
16 }
17}
18 
19const manager = new CryptographicKeyManager('secret_seed_42');
20console.log(manager.signPayload('transfer_funds')); // "hash_transfer_funds_secret_seed_42"
21// manager.#generateHash('test'); // SyntaxError!

4. Subclasses Cannot Access Private Fields!

Private fields are strictly private to the exact class in which they were declared. Derived subclasses cannot access private fields of their parent class:

1class Parent {
2 #secret = 'TopSecret';
3}
4 
5class Child extends Parent {
6 reveal() {
7 // return this.#secret; // SYNTAX ERROR! Private field '#secret' is not accessible in Child!
8 }
9}

5. Checking Private Fields with the in Operator (ES2022)

To safely check whether an unknown object contains a private field without throwing errors:

1class TokenValidator {
2 #token;
3 
4 constructor(token) {
5 this.#token = token;
6 }
7 
8 static isTokenValidator(obj) {
9 // Checks if obj contains the #token private brand
10 return #token in obj;
11 }
12}
13 
14console.log(TokenValidator.isTokenValidator(new TokenValidator('xyz'))); // true
15console.log(TokenValidator.isTokenValidator({})); // false

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What syntax defines a true private field in modern ECMAScript classes?
Question 2
What happens when code outside a class attempts to access an instance's private field (e.g. instance.#secret)?
Question 3
Can a derived subclass access private fields declared in its parent class?
Question 4
How can you check if an object contains a private field #key without throwing an exception?
Question 5
Does Object.getOwnPropertyNames(instance) or Object.keys(instance) reveal private fields?
Next Lesson

Prototypal Inheritance vs Class Inheritance

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Getters, Setters & Static MethodsPrototypal Inheritance vs Class Inheritance

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext