Better way of implementing public and private (#) fields in class in js

JavaScript classes have come a long way. Back in the old days (2015 πŸ’€), developers used all sorts of workarounds β€” closures, naming conventions, and even comments β€” to pretend something was private.

But today?
JavaScript finally gives us real private fields using the # symbol.
Let’s explore this in a fun, human way!


🧩 What Are Public & Private Fields?

Think of a class like a house:

  • Public fields = your living room
    β†’ Anyone can enter and see it.
  • Private fields = your secret cupboard
    β†’ Only the house owner (the class itself) can open it.

JavaScript now lets us create these secret cupboards cleanly.


πŸ”“ Public Fields (Easy & Friendly)

Public fields are visible to anyone using your class.

class User {
  name = "Amit"; // public field

  greet() {
    console.log(`Hello, I am ${this.name}!`);
  }
}

const u = new User();
u.greet();          // Hello, I am Amit!
console.log(u.name); // Accessible βœ”

Everything is open and accessible β€” great for normal data.


πŸ”’ Private Fields Using # (Modern, Clean & Safe)

Private fields are created by adding a # before the field name.

class BankAccount {
  #balance = 0; // private field

  deposit(amount) {
    this.#balance += amount;
  }

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

const acc = new BankAccount();
acc.deposit(500);
console.log(acc.getBalance()); // 500

console.log(acc.#balance); // ❌ ERROR: Private field

#balance can only be accessed inside the class β€” perfect for sensitive data.


⚑ Why Private Fields Are Better (vs old tricks)

Old ways developers tried to make things private:

  1. Using _underscore (just a naming convention πŸ‘€)
  2. Using closures (complex)
  3. Using Symbol() (hacky)
  4. Using WeakMaps (overkill)

Private fields with #:
βœ” Real privacy
βœ” Faster
βœ” Clean syntax
βœ” Supported in all modern browsers


🎯 Real-Life Example: Login System

class Login {
  #password;

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

  authenticate(inputPassword) {
    return this.#password === inputPassword;
  }
}

const user = new Login("Amit", "secret123");

console.log(user.authenticate("wrong")); // false
console.log(user.authenticate("secret123")); // true

console.log(user.#password); // ❌ Nope

This keeps your password hidden β€” like it should be!


πŸ› οΈ Example: Rate Limiter (Prevent Too Many Requests)

class RateLimiter {
  #limit = 5;
  #requests = 0;

  request() {
    if (this.#requests < this.#limit) {
      this.#requests++;
      return "Request allowed βœ”";
    }
    return "Too many requests ❌";
  }
}

const api = new RateLimiter();

console.log(api.request());
console.log(api.request());
console.log(api.#limit); // ❌ Private

Perfect for APIs and backend logic.


🧠 When Should You Use Private Fields?

Use private fields when you want to protect:

  • Passwords
  • Tokens
  • Internal counters
  • Calculations
  • Anything users shouldn’t directly modify

Public fields are fine for:

  • Display names
  • UI-visible data
  • Non-sensitive properties

🏁 Final Thoughts

Private fields (#name) are one of JavaScript’s best modern additions.
They keep your code clean, secure, and future-proof.

Use them when you want strict privacy.
Use public fields when you want flexibility.

By mixing both, you get the perfect class design β€” strong, readable, and safe.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *