JavaScript Fundamentals / Classes

Private Methods and Fields

✅ Private Fields & Methods

Private fields/methods are class members that are accessible only inside the class.

They are created using the # prefix.

✔ Prevents direct access

✔ Used for true encapsulation

✔ Not visible outside the class


👉 Private Fields

class User {
  #password; // private field

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

Access Rule

✅ Can be used only inside the class

❌ Cannot be accessed from outside

const u = new User("1234");
console.log(u.#password); // ❌ SyntaxError

⚠ Unlike _password, which is just a convention,

#password is actually protected by JavaScript.


👀 Private Methods

Used for internal helper logic.

class User {
  #encrypt(data) {           // private method
    return `***${data}***`;
  }

  save() {
    console.log(this.#encrypt("saved"));
  }
}

const u = new User();
u.save();              // ✅ works
u.#encrypt("test");    // ❌ SyntaxError

🔖 Why Use Private Members?

✔ Protect sensitive data

✔ Prevent accidental modification

✔ Control access through methods

✔ Keep class API clean


✅ Private Static Fields & Methods

Work at class level, not instance level.

class Counter {
  static #count = 0;   // private static field

  static #log() {      // private static method
    console.log(this.#count);
  }

  static increment() {
    this.#count++;
    this.#log();
  }
}

Counter.increment(); // ✅ prints 1
Counter.#count;      // ❌ error

🚀 Important Rules

✔ Must start with #

✔ Cannot be accessed outside the class

✔ Cannot be dynamically created (name must be known at compile time)

✔ Not inherited by subclasses

✔ Cannot be accessed with bracket notation (this["#password"] ❌)


✅ Private vs Protected vs Underscore

Type

Syntax

Actual Privacy

Meaning

Private

#name

✅ Enforced by JS

Only inside class

Underscore

_name

❌ Just convention

“Treat as internal”

Normal field

name

❌ Public

Anyone can access