JavaScriptAdvanced

JavaScript Private Fields (#) and Static Members Explained

Learn private fields and methods with #, static fields and static methods in JavaScript classes, with real examples like bank accounts and ID generators.

All JavaScript lessons (83)View curriculum

What you will learn

In the last two lessons you wrote classes and made children with extends. But one problem is still open: everything is public. Anyone can write account.balance = 99999999, and your carefully written withdraw() rules mean nothing.

In this lesson you will learn how to hide the inside of a class with private fields and methods (the # sign), so that only the class itself can change its important data. You will also learn static fields (data that belongs to the whole class), private static members, and the static initialization block. By the end you will be able to write classes that are safe, tidy and easy to use.

The problem: everything is public

class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
  }

  withdraw(amount) {
    if (amount > this.balance) {
      throw new Error("Not enough balance");
    }
    this.balance -= amount;
  }
}

const account = new BankAccount("Riya", 1000);

account.balance = 9999999;       // nothing stops this!
console.log(account.balance);    // 9999999

The class has a rule (no withdrawing more than you have), but outside code walks around the rule by changing balance directly.

In the classes lesson you used a name with an underscore (_marks) as a polite signal. But it is only a request, not a lock. Anyone can still write account._marks = 999.

In the constructor functions lesson you saw a closure trick that hid balance, but it created every method again for every object. Now JavaScript has a built-in answer.

The idea in one line

A name that starts with # is private: only code written inside the class can read or change it.

Think of an ATM. You can press buttons (deposit, withdraw, check balance), but you cannot open the machine and touch the money inside. The buttons are the public part. The cash box is private. This idea has a name: encapsulation, which means keep the inside hidden and offer a safe way to use it.

Private fields with #

A private field must be declared in the class body with # in front of its name. You use it with this.#name.

class BankAccount {
  #balance = 0;                    // declared: a private field

  constructor(owner, startBalance = 0) {
    this.owner = owner;            // public
    this.#balance = startBalance;  // private
  }

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

  get balance() {                  // a getter: safe read-only access
    return this.#balance;
  }
}

const account = new BankAccount("Riya", 1000);
account.deposit(500);

console.log(account.balance);      // 1500 (read through the getter)

Now try to reach in from outside:

// console.log(account.#balance);   // SyntaxError: Private field '#balance' must be declared in an enclosing class
// account.#balance = 99999;        // SyntaxError as well

This is not a normal runtime error. It is a SyntaxError, so the code does not even start. That is the strongest kind of protection. And some other ways of peeking find nothing:

console.log(account["#balance"]);      // undefined (this is just a normal key called "#balance")
console.log(Object.keys(account));     // ["owner"]  (private fields are not listed)
console.log(JSON.stringify(account));  // {"owner":"Riya"}

Remember: #balance and balance are two different names. The # is a part of the name. In the example above we have a private #balance and a public getter balance, which is a very common pattern.

You must declare it first

A private field must be declared at the top of the class. You cannot create one later by assigning:

class Wrong {
  constructor() {
    // this.#secret = 1;   // SyntaxError: Private field '#secret' must be declared in an enclosing class
  }
}

(A normal public property can be created anywhere. A private one cannot. That is how JavaScript can check it for you before running the code.)

Private fields vs the _underscore habit

_balance (convention) #balance (private field)
Can outside code read it? Yes, if it ignores the hint No: SyntaxError
Can outside code change it? Yes No
Shows in Object.keys and JSON.stringify Yes No
Needs declaring in the class No Yes
Child classes can use it Yes No (see below)

Private fields and the closure trick

Closure in constructor (old trick) # private field
Truly hidden Yes Yes
Methods shared on the prototype No (copy per object) Yes
Clean syntax Not really Yes

Private methods

A method can be private too. Use it for helper work that outsiders should never call.

class PasswordChecker {
  #minLength = 8;

  #hasNumber(text) {
    return /\d/.test(text);
  }

  #hasUpperCase(text) {
    return /[A-Z]/.test(text);
  }

  isStrong(password) {
    return (
      password.length >= this.#minLength &&
      this.#hasNumber(password) &&
      this.#hasUpperCase(password)
    );
  }
}

const checker = new PasswordChecker();

console.log(checker.isStrong("abc"));          // false
console.log(checker.isStrong("Secret123"));    // true
// checker.#hasNumber("x");                    // SyntaxError: not allowed outside the class

Only isStrong is the public menu. The small helpers stay hidden, so you can change or rename them later without breaking anyone’s code.

Getters and setters can be private as well:

class Circle {
  #radius;

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

  get #diameter() {                 // private getter
    return this.#radius * 2;
  }

  describe() {
    return "Diameter is " + this.#diameter;
  }
}

console.log(new Circle(5).describe());   // "Diameter is 10"

A safe setter: validation with real privacy

In the classes lesson, the _marks setter could be bypassed. Now we can protect it properly:

class Student {
  #marks = 0;

  constructor(userName, marks) {
    this.userName = userName;
    this.marks = marks;            // goes through the setter
  }

  get marks() {
    return this.#marks;
  }

  set marks(value) {
    if (typeof value !== "number" || value < 0 || value > 100) {
      throw new RangeError("Marks must be a number from 0 to 100");
    }
    this.#marks = value;
  }
}

const riya = new Student("Riya", 85);

try {
  riya.marks = 150;                 // the setter rejects it
} catch (error) {
  console.log(error.message);       // "Marks must be a number from 0 to 100"
}

console.log(riya.marks);            // 85 (unchanged)

Nobody can set #marks without passing the check.

Do not leak private data by accident

A getter that returns a private array or object gives away the real thing, because of reference behaviour. The outside code can then change your “private” data.

class Wishlist {
  #items = [];

  add(item) {
    this.#items.push(item);
    return this;
  }

  get itemsLeaky() {
    return this.#items;             // returns the REAL array
  }

  get items() {
    return [...this.#items];        // returns a COPY
  }
}

const list = new Wishlist();
list.add("Pen").add("Bag");

list.itemsLeaky.push("Stolen!");    // changes the real private array
console.log(list.itemsLeaky);       // ["Pen", "Bag", "Stolen!"]

list.items.push("Another");         // changes only a copy
console.log(list.items);            // ["Pen", "Bag", "Stolen!"]  (the copy changes nothing)

Return a copy ([...array], { ...object }), or a frozen object, when the data must stay safe. (A shallow copy protects the list itself, not the objects inside it. You learned this in the value vs reference lesson.)

Private fields and inheritance

Private fields belong only to the class that declares them. A child class (from the inheritance lesson) cannot reach its parent’s private fields:

class Parent {
  #secret = "parent secret";

  reveal() {
    return this.#secret;            // fine: inside Parent
  }
}

class Child extends Parent {
  tryToRead() {
    // return this.#secret;         // SyntaxError: Child never declared #secret
    return this.reveal();           // the right way: use the parent's public method
  }
}

console.log(new Child().tryToRead());   // "parent secret"

The child must use the parent’s public methods and getters. This keeps the parent in full control of its own data.

Even if both classes use the same #name, they are two separate private fields:

class P {
  #x = 1;
  getParentX() { return this.#x; }
}

class C extends P {
  #x = 2;
  getChildX() { return this.#x; }
}

const c = new C();
console.log(c.getParentX());   // 1
console.log(c.getChildX());    // 2

Checking for a private field: #x in obj

How do you know whether an object really was created by your class? Use the in operator with a private name, inside the class:

class Account {
  #balance = 0;

  static isAccount(value) {
    return #balance in value;
  }
}

console.log(Account.isAccount(new Account()));   // true
console.log(Account.isAccount({}));              // false

This is more trustworthy than instanceof, which can be fooled by changing prototypes.

Static fields

You know static methods from the classes lesson: they belong to the class itself. A static field is the same idea for data: one value for the whole class, not one per object.

class User {
  static count = 0;                              // shared by all users
  static ROLES = ["student", "teacher", "admin"];

  constructor(userName) {
    this.userName = userName;
    User.count++;                                // update the shared counter
  }
}

new User("Riya");
new User("Karan");

console.log(User.count);       // 2
console.log(User.ROLES[2]);    // "admin"

Compare the two kinds of fields:

Instance field Static field
Written as balance = 0; static count = 0;
Copies One per object One for the class
Read with object.balance ClassName.count
Good for Each object’s own data Counters, constants, settings, caches

It is the clean class version of the Student.total = 0 trick from the constructor functions lesson. Built-in examples: Number.MAX_SAFE_INTEGER, Math.PI.

Constants: freeze them

If a static field should never change, freeze it (you know Object.freeze from the Object methods lesson):

class Order {
  static STATUS = Object.freeze({
    PENDING: "pending",
    SHIPPED: "shipped",
    DELIVERED: "delivered"
  });
}

console.log(Order.STATUS.SHIPPED);   // "shipped"

Static fields and inheritance: a trap

A child class can read a parent’s static field through the chain, but writing creates its own property. This is exactly the “shadowing” behaviour from the prototypes lesson, now between classes.

class User {
  static count = 0;
}

class Admin extends User {}

console.log(Admin.count);          // 0  (read: found on User through the chain)

Admin.count++;                     // read 0, then WRITE 1 on Admin itself

console.log(Admin.count);          // 1
console.log(User.count);           // 0  (User was not changed!)
console.log(Object.hasOwn(Admin, "count"));   // true

If you want one shared counter for the whole family, always use the parent’s name: User.count++.

Private static members

A static field or method can be private too. This is perfect for internal counters and helpers that the outside world should not touch.

class Ticket {
  static #nextId = 1;                  // private static field

  static #format(id) {                 // private static method
    return "TKT-" + String(id).padStart(4, "0");
  }

  constructor(title) {
    this.title = title;
    this.id = Ticket.#format(Ticket.#nextId++);
  }
}

console.log(new Ticket("Login bug").id);      // "TKT-0001"
console.log(new Ticket("Slow page").id);      // "TKT-0002"
// console.log(Ticket.#nextId);               // SyntaxError: it is private

Nobody can reset the counter or create two tickets with the same id.

Gotcha: inside a static method, use the class name (Ticket.#nextId), not this.#nextId. If the method is called through a child class, this is the child, which does not have that private field, and you get a TypeError.

class Base {
  static #secret = 42;

  static readWrong() {
    return this.#secret;     // breaks when called as Child.readWrong()
  }

  static readRight() {
    return Base.#secret;     // always works
  }
}

class Child extends Base {}

console.log(Child.readRight());   // 42

try {
  Child.readWrong();
} catch (error) {
  console.log(error.name);        // "TypeError"
}

Static initialization blocks

Sometimes setting up a static field needs more than one line. A static { ... } block runs once, when the class is created:

class Squares {
  static table = [];

  static {
    for (let i = 1; i <= 10; i++) {
      Squares.table.push(i * i);
    }
  }
}

console.log(Squares.table[0]);   // 1
console.log(Squares.table[9]);   // 100

It is handy for building lookup tables or doing one-time setup. You will not need it often, but it is good to know.

Real-life use cases

1. A safe bank account

class BankAccount {
  #balance = 0;
  #history = [];

  constructor(owner, startBalance = 0) {
    this.owner = owner;
    this.#balance = startBalance;
  }

  #validate(amount) {
    if (typeof amount !== "number" || amount <= 0) {
      throw new RangeError("Amount must be more than 0");
    }
  }

  deposit(amount) {
    this.#validate(amount);
    this.#balance += amount;
    this.#history.push({ type: "deposit", amount });
    return this;
  }

  withdraw(amount) {
    this.#validate(amount);
    if (amount > this.#balance) {
      throw new Error("Not enough balance");
    }
    this.#balance -= amount;
    this.#history.push({ type: "withdraw", amount });
    return this;
  }

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

  get history() {
    return this.#history.map((entry) => ({ ...entry }));   // copies of copies
  }
}

const account = new BankAccount("Riya", 1000);
account.deposit(500).withdraw(300);

console.log(account.balance);          // 1200
console.log(account.history.length);   // 2

The only way to change money is through deposit and withdraw, which always run the checks.

2. A unique ID generator

class Id {
  static #next = 1;

  static create(prefix = "id") {
    return prefix + "-" + Id.#next++;
  }
}

console.log(Id.create("user"));    // "user-1"
console.log(Id.create("order"));   // "order-2"
console.log(Id.create());          // "id-3"

3. A stopwatch that hides its timer

class Stopwatch {
  #seconds = 0;
  #timerId = null;

  start() {
    if (this.#timerId !== null) return this;     // already running

    this.#timerId = setInterval(() => {
      this.#seconds++;
      console.log("Seconds: " + this.#seconds);
    }, 1000);

    return this;
  }

  stop() {
    clearInterval(this.#timerId);
    this.#timerId = null;
    return this;
  }

  get seconds() {
    return this.#seconds;
  }
}

const watch = new Stopwatch();
watch.start();
setTimeout(() => watch.stop(), 3500);   // prints 1, 2, 3 and stops

Outside code cannot accidentally overwrite #timerId and make the timer impossible to stop. The arrow function inside setInterval keeps this, as you learned in the first lesson of this section.

4. A logger that counts and limits itself

class Logger {
  static #count = 0;
  static LEVELS = Object.freeze(["info", "warn", "error"]);

  static log(level, message) {
    if (!Logger.LEVELS.includes(level)) {
      throw new RangeError("Unknown level: " + level);
    }
    Logger.#count++;
    console.log("[" + level.toUpperCase() + "] " + message);
  }

  static get total() {
    return Logger.#count;
  }
}

Logger.log("info", "App started");
Logger.log("error", "Payment failed");

console.log(Logger.total);   // 2

A class that has only static members is used like a small toolbox, such as Math or JSON.

5. A single shared settings object (singleton)

class Settings {
  static #instance = null;
  #values = { theme: "light", language: "en" };

  static get() {
    if (Settings.#instance === null) {
      Settings.#instance = new Settings();
    }
    return Settings.#instance;
  }

  set(key, value) {
    this.#values[key] = value;
    return this;
  }

  read(key) {
    return this.#values[key];
  }
}

Settings.get().set("theme", "dark");

console.log(Settings.get().read("theme"));       // "dark"
console.log(Settings.get() === Settings.get());  // true: always the same object

What private fields cannot do

Be aware of these limits:

  • They are truly private: even your own debugging code and tests cannot read them from outside. Test the public behaviour instead.
  • They are not copied by { ...object }, Object.assign or JSON.stringify, because they are not normal properties.
  • They are not inherited by child classes.
  • You cannot create them dynamically (this["#x"] is just a normal property called "#x"), and you cannot delete them.
  • Using a private method on the wrong object (for example, by losing this) throws a TypeError:
class Counter {
  #count = 0;

  increase() {
    this.#count++;
    return this.#count;
  }
}

const counter = new Counter();
const lost = counter.increase;

try {
  lost();                     // this is undefined: it cannot reach #count
} catch (error) {
  console.log(error.name);    // "TypeError"
}

setTimeout(() => console.log(counter.increase()), 0);   // 1: an arrow wrapper keeps this

You already know the fixes from the call, apply and bind lesson.

How much of this to use?

A good rule: make things private by default, and make public only what other code truly needs.

Put in the public menu Keep private (#)
Actions others need (deposit(), start()) Internal state (#balance, #timerId)
Safe read access (getters) Helper methods (#validate())
Settings others should be able to change Anything you may want to rename or redesign later

A small public surface means fewer ways to break your class, and more freedom to improve the inside later.

The OOP journey so far

Lesson The big idea
this, call, apply, bind this can be set by hand, and methods can be borrowed
Prototypes Objects link to other objects and look up properties along a chain
Constructor functions new builds objects that share prototype methods
Classes A clean syntax for the same thing, with getters, setters and static methods
Class inheritance extends and super reuse and change a parent’s behaviour
Private fields and static members # hides the inside. static shares data across the whole class

You can now read and write almost all the object-oriented JavaScript used in real projects.

Common mistakes

  • Using a private field without declaring it at the top of the class. It is a SyntaxError.
  • Trying to read object.#field from outside the class. It is a SyntaxError. Add a getter or a method instead.
  • Confusing #balance with balance. They are different names.
  • Returning a private array or object from a getter and thinking it is safe. Return a copy.
  • Expecting a child class to use the parent’s #field. Use public methods or getters.
  • Using this.#staticField inside a static method that may be called from a child class. Use the class name.
  • Incrementing a static field through a child (Admin.count++). It creates a separate copy on the child. Use User.count++.
  • Losing this in a method that uses private fields. You get a TypeError.
  • Expecting JSON.stringify or the spread operator to include private fields. They do not.
  • Making everything private, even simple data that others should read. Offer getters for that.
  • Using static for data that should be different for each object. Use an instance field instead.

Practice

  1. Take a BankAccount class with a public balance. Prove that outside code can set balance = 9999999. Then rewrite it with a private #balance.
  2. Add a getter balance that only reads. Try to assign to it, and check the result.
  3. Add a private method #validate(amount) and use it in both deposit and withdraw.
  4. Try to read account.#balance from outside, read the SyntaxError, and then comment it out.
  5. Print account["#balance"], Object.keys(account) and JSON.stringify(account). Explain why the private field never shows.
  6. Write a Wishlist class with a private array. Make one getter that leaks the real array and one that returns a copy. Prove the difference.
  7. Write a Student with a private #marks and a setter that rejects numbers outside 0 to 100.
  8. Create a Parent with a private field and a Child that tries to read it. Fix the child using a public method.
  9. Create a P and a C that both declare #x. Show that getParentX() and getChildX() give different values.
  10. Write static isAccount(value) using #balance in value. Test it with an account, a plain object and null (what do you need to add for null?).
  11. Add a static field static count = 0 to a User class. Increase it in the constructor and print it after creating three users.
  12. Add a frozen static object ROLES and try to change it.
  13. Write a Ticket class with a private static counter and a private static formatter, so ids look like TKT-0001.
  14. Create Admin extends User, then run Admin.count++. Print User.count and Admin.count, and Object.hasOwn(Admin, "count"). Explain what happened. Then fix it with User.count++.
  15. Write a static method that uses this.#secret, call it on a child class, and read the error. Fix it with the class name.
  16. Use a static { } block to build a lookup table of square numbers from 1 to 10.
  17. Challenge: write a Stopwatch with a private timer id and private seconds, start(), stop() and reset(), and a getter seconds. Make sure calling start() twice does not start two timers.
  18. Challenge: write a Settings singleton with a private static instance and a private #values object. Prove that two calls to Settings.get() return the same object.
  19. Challenge: write a PasswordChecker with a private minimum length and at least three private helper methods. Only isStrong(password) should be public.
  20. Challenge: write a Cart class with a private array of items, add, remove, a total getter and an items getter that returns copies of the items. Prove that outside code cannot change the cart.

Recap

  • Private fields start with # and must be declared in the class body. Only code inside the class can read or change them. Reaching in from outside is a SyntaxError.
  • This is encapsulation: keep the inside hidden, and offer a small public menu of methods and getters.
  • Private methods (#helper() {}) and private getters and setters hide helper work.
  • A private field is truly private: not visible in Object.keys, JSON.stringify or the spread operator, and not inherited by child classes. Children use the parent’s public methods.
  • Do not leak a private array or object through a getter. Return a copy.
  • #field in object is a reliable way to check that an object was made by your class.
  • Static fields (static count = 0) hold data for the whole class, such as counters, constants and settings. Freeze constants with Object.freeze.
  • Private static members (static #next) hide internal counters and helpers. Inside static methods, use the class name, not this, to reach them.
  • A child class can read a parent’s static field, but writing to it through the child creates a separate copy. Update shared values through the parent.
  • A static { } block runs once and is useful for multi-step setup.
  • Make things private by default, and public only when others truly need them.
  • You have completed the classes and OOP part of the course. Next you will learn modules: how to split your code into files with import and export, so bigger projects stay organised.

If you want to revisit the basics, read the classes lesson, the class inheritance lesson, the prototypes lesson and the value vs reference lesson.

Frequently asked questions

What is a private field in JavaScript?

A private field is a class property whose name starts with #, such as #balance. It must be declared in the class body, and only code inside that class can read or write it. Trying to use it from outside is a syntax error.

What is the difference between _name and #name?

An underscore is only a naming habit that asks others not to touch the property, but anyone still can. A # name is enforced by the language: code outside the class cannot access it at all.

Can a child class access a parent's private field?

No. Private fields belong only to the class that declares them. The child class must use the parent’s public methods or getters to work with that data.

What is a static field?

A static field is a property that belongs to the class itself instead of each object. It is declared with static, such as static count = 0, and read with the class name, such as User.count. It is useful for counters, constants and shared settings.

Why does Admin.count++ not change User.count?

Reading Admin.count finds the value on User through the chain, but the write creates a new property on Admin itself. To change the shared value, write to the parent class: User.count++.

Why can't I see private fields when I use JSON.stringify or the spread operator?

Private fields are not normal properties. They are not listed by Object.keys, copied by spread or Object.assign, or included by JSON.stringify. If you need to export the data, add a public getter or a method that returns it.

See also: Classes, Class Inheritance, Value vs Reference, JavaScript Cheat Sheet