Learn JavaScript
❯ classes_oop.static_private

Static & Private (#) Members in JavaScript

$concept

Static members belong to the class (Counter.count, Config.load()) — shared utilities, factories, and class-wide state accessed without instances. Private fields (#balance) enforce true encapsulation: inaccessible outside the class body, invisible to subclass code and reflection, with private methods (#validate()) completing the pattern.

# privacy is hard (runtime-enforced, unlike _convention or TypeScript private), and static initialization blocks (static { ... }) run complex class-level setup. Together they express shared-vs-instance and public-vs-hidden cleanly.

$how it works
1

Static belongs to the class

Counter.total reads without new Counter() — factories, constants, and shared state live here.

2

# is truly private

#balance is unreachable outside the class body — stronger than _convention, enforced at runtime.

3

Static blocks initialize

static { ... } runs once at class definition for computed statics — registries, caches, validation.

4

Subclasses excluded too

# fields stay invisible to derived classes — intentional hiding, bridged via protected-style methods when needed.

$example
class Counter {
static total = 0;
#n = 0;
bump() {
this.#n++;
Counter.total++;
return this.#n;
}
}
let c = new Counter();
console.log(c.bump(), Counter.total);
Output
1 1
1Static total lives on the class; #n lives privately per instance.
2bump increments both — private instance state plus shared class state.
31 1 prints — two ownership levels cooperating.
$use cases
Factory methods and shared constants as statics
True privacy with # for sensitive state
Class-wide registries initialized in static blocks
Distinguishing # privacy from _ naming convention

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.