Labs ICT
Pro Login

Private Fields

2 min read | JavaScript Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Private Fields

In JavaScript, class properties are public by default — anyone can read or modify them. Private fields let you restrict access to certain properties, keeping them hidden outside the class. You create them using the # prefix.

class BankAccount {
  #balance = 0;

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

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

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

const account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance()); // 1500
console.log(account.#balance); // ❌ SyntaxError!

Why Use Private Fields?

Private fields protect the internal state of your class. Without them, external code could put your object into an invalid state. For example, setting a negative balance on a bank account.

class User {
  #password;

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

  checkPassword(guess) {
    return guess === this.#password;
  }
}

const user = new User("alice", "secret123");
console.log(user.username); // "alice" — public
console.log(user.#password); // ❌ Can't access!

Private Methods

You can also make methods private using the # prefix. This is useful for helper methods that shouldn't be called from outside.

class TemperatureConverter {
  #toCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5 / 9;
  }

  convert(fahrenheit) {
    return this.#toCelsius(fahrenheit);
  }
}

const converter = new TemperatureConverter();
console.log(converter.convert(212)); // 100
console.log(converter.#toCelsius(212)); // ❌ Not accessible

Comparison with Underscore Convention

Before private fields, developers used underscore prefixes like _balance to signal "private" properties. But that was just a convention — the property was still accessible. The # prefix is enforced by the language.

class OldStyle {
  constructor() {
    this._secret = "kind of private"; // Just a convention
  }
}

const obj = new OldStyle();
console.log(obj._secret); // Still accessible!

Summary

Private fields (#) give you true encapsulation in JavaScript classes. Use them to protect internal state and expose only what's necessary through public methods.