Course contentsShow
← JavaScript
Lesson 792 of 2,72318. ClassesFree lesson

Private Static Fields

Understand how to define private static fields that are shared across all instances but inaccessible externally.

Private Static Fields

You'll learn how to create class-level data that's shared across all instances but completely hidden from external code.

Understanding Private Static Fields

Private static fields combine two powerful concepts: the # privacy syntax with the static keyword. These fields belong to the class itself (not individual instances) and are accessible only within the class body—no external code can see or modify them.

Think of a private static field like a secret vault in a company's headquarters. All employees (instances) can access it through authorized channels (class methods), but outsiders have no way to even detect its existence.

How They Work

You declare a private static field by combining static with the # prefix:

class Counter {
  static #totalCount = 0;
  #instanceId;

  constructor() {
    Counter.#totalCount++;
    this.#instanceId = Counter.#totalCount;
  }

  getInstanceId() {
    return this.#instanceId;
  }

  static getTotalCount() {
    return Counter.#totalCount;
  }
}

const obj1 = new Counter();
const obj2 = new Counter();

console.log(Counter.getTotalCount()); // 2
console.log(obj1.getInstanceId());    // 1
console.log(obj2.getInstanceId());    // 2

// console.log(Counter.#totalCount);  // SyntaxError!

Here, #totalCount is shared across all instances but completely inaccessible from outside. Only the class's own static and instance methods can read or modify it.

Common Use Cases

Private static fields excel at tracking class-wide information like instance counts, caching shared data, or storing configuration that shouldn't be tampered with externally.

Key Takeaway: Private static fields (static #fieldName) create class-level data that's shared by all instances but remains completely hidden from external access, perfect for internal bookkeeping and shared secrets.