0
0
JavascriptConceptBeginner · 3 min read

Private Fields in JavaScript Class: What They Are and How to Use

Private fields in JavaScript classes are properties that can only be accessed or changed inside the class itself. They are declared with a # prefix and help keep data hidden from outside code, improving security and design.
⚙️

How It Works

Think of a JavaScript class like a blueprint for making objects, similar to how a recipe guides cooking. Private fields are like secret ingredients only the chef (the class) knows about and uses. They start with a # symbol and cannot be touched or seen from outside the class, which keeps them safe from accidental changes.

This means if you try to access or change a private field from outside the class, JavaScript will give an error. This helps programmers protect important data and control how it changes, making code more reliable and easier to maintain.

💻

Example

This example shows a class with a private field #secret. Only methods inside the class can read or update it.

javascript
class SecretKeeper {
  #secret;

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

  revealSecret() {
    return `The secret is: ${this.#secret}`;
  }
}

const keeper = new SecretKeeper('JavaScript rocks!');
console.log(keeper.revealSecret());
// Trying to access private field directly will cause an error
// console.log(keeper.#secret); // SyntaxError
Output
The secret is: JavaScript rocks!
🎯

When to Use

Use private fields when you want to hide data inside a class so no outside code can change it directly. This is useful for sensitive information like passwords, internal counters, or any data that should only be changed in controlled ways.

For example, in a banking app, you might keep the account balance private and only allow changes through deposit or withdrawal methods. This prevents bugs or security issues caused by accidental or unauthorized changes.

Key Points

  • Private fields start with # and are only accessible inside the class.
  • Trying to access private fields outside the class causes errors.
  • They help protect data and enforce controlled access.
  • Private fields improve code safety and maintainability.

Key Takeaways

Private fields use a # prefix and are only accessible inside their class.
They prevent outside code from reading or changing sensitive data directly.
Use private fields to protect important internal state and avoid bugs.
Access private fields only through class methods for controlled updates.