Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 156 ยท Classes and Objects in Depth

Private Fields and Static Members

Protect class internals with #private fields and methods, add static methods and fields that belong to the class itself, and run setup code with static blocks.

The classes you have written so far expose everything. Any code can reach into a Temperature and set _celsius to "banana", skipping the setter you carefully wrote. The underscore is only a polite request. And sometimes you need data or helper functions that belong to the class as a whole, not to any single instance: a counter of how many objects were created, a factory method, a table of constants.

JavaScript classes solve both problems with two features. Private members, written with a # prefix, can only be touched by code inside the class body. Static members, written with the static keyword, live on the class itself. This lesson covers both, plus static initialization blocks.

Private fields with #

Put # in front of a field name to make it private. The # is part of the name: you declare it as #balance in the class body and use it as this.#balance in methods. Outside the class, the field simply cannot be reached:

JS A private field

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Private fields are not ordinary properties with a funny name. They are stored separately, so they never appear in Object.keys(), for...in, JSON.stringify() or spread copies, and wallet["#balance"] looks for a completely unrelated public property.

What happens if outside code writes wallet.#balance? The program doesn't even start. Using a private name outside the class that declares it is a SyntaxError, caught when the code is parsed:

JavaScript
class Wallet { #balance = 0; }
const w = new Wallet();
console.log(w.#balance);
// SyntaxError: Private field '#balance' must be declared in an enclosing class

Private fields must be declared in the class body. You can't create one on the fly in the constructor the way you can with this.anything = ....

Support: private fields, private methods and private accessors are supported in all current browsers (Chrome 84+, Firefox 90+, Safari 15+) and Node.js 14.6+. They have been safe to use without a build step for several years.

Private methods and accessors

Methods, getters and setters can be private too. Private methods are great for internal helpers that are not part of the class's public interface, so you can rename or rewrite them without breaking anyone:

JS Private methods and validation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is the finished version of the Temperature class from the Classes lesson. Now there is no way to sneak an invalid value past the setter.

Privacy is per class, not per object

Code inside a class can read the private fields of any instance of that class, not just this. That is useful for methods that compare or combine two instances:

JavaScript
class Money {
  #cents;
  constructor(cents) { this.#cents = cents; }
  equals(other) { return this.#cents === other.#cents; }
}

If other is not a Money object, reading other.#cents throws a TypeError. To check first, use the in operator with the private name. It returns true only for objects that have that private field:

JavaScript
static isMoney(value) {
  return #cents in value;
}

This brand check is a reliable way to say "was this object really created by my class?", and it can't be faked the way instanceof can.

Subclasses can't see the parent's privates

Private members are visible only inside the class body that declares them. A subclass created with extends inherits the parent's public methods, and those methods can still use the private fields, but code written in the subclass cannot write this.#balance. If subclasses need access, provide a public (or clearly documented) method or getter in the parent.

Static methods

A static method belongs to the class itself, not to instances. You call it on the class name, and inside it, this refers to the class. Static methods are the natural home for:

  • Factory methods: alternative ways to create instances, such as fromJSON() or fromString().
  • Utilities related to the class that don't need an instance, like the built-in Array.isArray(), Number.parseFloat() or Object.keys().
JS Static methods and fields

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Inside fromHex, new this(...) creates an instance of whichever class the method was called on. If a subclass inherits fromHex, calling SubColor.fromHex() creates a SubColor. Writing new Color(...) would always create a plain Color.

Static fields are evaluated in order, from top to bottom, when the class is defined. static WHITE = new Color(...) works because the constructor already exists at that point, and it even counts toward #created. The order matters: if #created were declared after WHITE, the constructor would try to update a private field that doesn't exist yet and throw a TypeError. Static members can be private too, like static #created here.

Static fields

Static fields hold data shared by the whole class: configuration, constants, caches and counters. They are created once, when the class definition runs, not once per instance:

JavaScript
class Http {
  static TIMEOUT_MS = 5000;
  static #cache = new Map();
}

Http.TIMEOUT_MS; // 5000

Use them for values that are truly class-wide. Data that varies per object belongs in normal instance fields.

Static initialization blocks

Sometimes a static field needs more than a single expression to set up: a loop, a try...catch, or several fields computed together. A static block, written static { ... }, runs once when the class is defined, with this set to the class. It can also read and write private static fields:

JS A static initialization block

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The message is printed before anything else uses the class, which shows that the block runs as part of defining it. A class can have several static blocks; they run in order, interleaved with static field initializers.

Support: static blocks arrived in ES2022 and work in Chrome and Edge 94+, Firefox 93+, Safari 16.4+ and Node.js 16.11+.

When to use what

  • Make fields private by default when they hold state that must stay consistent. Expose only what callers need, preferably through methods and getters.
  • Use private methods for internal steps that callers should never call directly.
  • Use static methods for factories and class-related helpers that don't need an instance.
  • Use static fields for constants and class-wide data; use a static block when setting them up needs several statements.
  • Don't make everything static. If a class has only static members, a plain object or a module of functions is usually simpler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class declares #count = 0. What happens if code outside the class writes obj.#count?

    Private names can only be used inside the class body that declares them. Anywhere else, the parser rejects the code with a SyntaxError.
  2. 2. What does JSON.stringify(new Wallet()) include, if Wallet has only the private field #balance?

    Private fields are not properties, so JSON.stringify, Object.keys and spread never see them.
  3. 3. Where do you call a static method named fromHex?

    Static methods live on the class itself. Instances don't inherit them, so color.fromHex is undefined.
  4. 4. What does #cents in value check?

    The in operator with a private name is a brand check: it is true only for objects that carry that private field.
  5. 5. When does a static { ... } block run?

    Static blocks run once, as the class is being defined, with this set to the class.

Summary

  • #name makes a field, method or accessor private: usable only inside the class body, invisible to Object.keys, JSON and spread.
  • Accessing a private name outside its class is a SyntaxError; reading it from the wrong kind of object is a TypeError.
  • Code in a class can read the private fields of any instance of that class; #field in obj is a reliable brand check.
  • static methods and fields belong to the class itself; use them for factories, utilities, constants and counters.
  • In a static method, this is the class, so new this() respects subclasses.
  • static { ... } blocks run once during class definition for multi-step setup.

Next: Composition over Inheritance โ€” building objects from small pieces of behavior.