Course contentsShow
← JavaScript
Lesson 1988 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Private Static Fields and Methods

Using # with static members to create private class-level data and utilities.

Private Static Fields and Methods

You'll learn how to use the # prefix with static to create private, class-level data and helper functions that only the class itself can access.

What Are Private Static Members?

Just as you can have private instance fields (#name) that belong to individual objects, you can also have private static fields and methods that belong to the class itself, not to any specific instance. These are shared across all instances but remain completely hidden from outside code.

Think of it like a company's internal policy manual. Regular private fields are like each employee's personal notes—unique to them. Private static members are like classified company procedures—shared by the organization, but kept confidential from the public.

Syntax

Combine # with static:

class Counter {
  static #instanceCount = 0;
  
  static #logCreation() {
    console.log(`Instance #${this.#instanceCount} created`);
  }
  
  constructor() {
    Counter.#instanceCount++;
    Counter.#logCreation();
  }
  
  static getCount() {
    return this.#instanceCount;
  }
}

const c1 = new Counter(); // "Instance #1 created"
const c2 = new Counter(); // "Instance #2 created"
console.log(Counter.getCount()); // 2

// Counter.#instanceCount; // SyntaxError: Private field

Private static members are accessed using the class name or this (inside static methods), never through instances. They're perfect for internal counters, caches, configuration, or helper utilities that support the class but shouldn't be exposed.

Key Takeaway: Private static fields and methods (static #name) create class-level data and utilities that are shared across all instances but completely inaccessible from outside the class—ideal for internal bookkeeping and hidden implementation details.