[{"data":1,"prerenderedAt":145},["ShallowReactive",2],{"qa-\u002Fjavascript\u002Fclasses\u002Fstatic-private":3},{"page":4,"siblings":129,"blog":142},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":120,"seo":121,"seoDescription":122,"stem":123,"subtopic":124,"topic":125,"topicSlug":126,"updated":127,"__hash__":128},"qa\u002Fjavascript\u002Fclasses\u002Fstatic-private.md","Static Private",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"hard","md","JavaScript","javascript",{},true,3,"\u002Fjavascript\u002Fclasses\u002Fstatic-private",[23,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116],{"id":24,"difficulty":25,"q":26,"a":27},"static-members","medium","What are static members?","Members (methods or fields) that belong to the **class itself**, not to\ninstances. Accessed as `ClassName.member`.\n\n```js\nclass MathUtil {\n  static PI = 3.14159\n  static square(n) { return n * n }\n}\nMathUtil.PI          \u002F\u002F 3.14159\nMathUtil.square(4)   \u002F\u002F 16\nnew MathUtil().square \u002F\u002F undefined — not on instances\n```\n\nStatics suit utilities and class-level data that don't depend on a particular\ninstance. They're shared (one copy on the class) and inherited by subclasses.\n",{"id":29,"difficulty":25,"q":30,"a":31},"static-methods-use","When do you use a static method?","For operations related to the class but not to a specific instance — most\ncommonly **factory methods** and utilities.\n\n```js\nclass User {\n  constructor(name) { this.name = name }\n  static fromJSON(json) { return new User(JSON.parse(json).name) }\n  static compare(a, b) { return a.name.localeCompare(b.name) }\n}\nconst u = User.fromJSON('{\"name\":\"Ada\"}')\n```\n\nStatic factory methods (`User.fromJSON`, `Array.from`, `Promise.resolve`) are a\ncommon alternative to overloaded constructors. `this` inside a static method is\nthe class.\n",{"id":33,"difficulty":25,"q":34,"a":35},"static-fields","What are static fields?","Class-level properties declared with `static`, shared across all instances and\nthe class — useful for constants, counters, or caches.\n\n```js\nclass Counter {\n  static count = 0           \u002F\u002F shared\n  constructor() { Counter.count++ }\n}\nnew Counter(); new Counter()\nCounter.count   \u002F\u002F 2\n```\n\nReference them via the class name (`Counter.count`), not `this` (in instance\nmethods `this` is the instance). Static fields are a newer feature; older code\nused `Class.prop = value` after the class.\n",{"id":37,"difficulty":25,"q":38,"a":39},"this-in-static","What is this inside a static method?","The **class itself** — so static methods can call sibling statics and respect\nsubclassing.\n\n```js\nclass Base {\n  static create() { return new this() }   \u002F\u002F `this` is the class\n}\nclass Sub extends Base {}\nBase.create()   \u002F\u002F Base instance\nSub.create()    \u002F\u002F Sub instance — `this` is Sub\n```\n\nBecause `this` is the concrete class, a static factory like `create()` builds an\ninstance of whichever subclass it was called on — useful for polymorphic\nfactories.\n",{"id":41,"difficulty":25,"q":42,"a":43},"private-fields","What are private fields and how do you declare them?","Fields prefixed with `#` are **truly private** — accessible only inside the\nclass body, enforced by the language (not a convention).\n\n```js\nclass Account {\n  #balance = 0\n  deposit(n) { this.#balance += n }\n  get balance() { return this.#balance }\n}\nconst a = new Account()\na.#balance         \u002F\u002F SyntaxError outside the class\na.balance          \u002F\u002F via the getter\n```\n\nUnlike the `_underscore` convention, `#private` can't be accessed or even\ndetected from outside. It's real encapsulation built into the syntax.\n",{"id":45,"difficulty":25,"q":46,"a":47},"private-vs-underscore","What is the difference between","`_name` is a **convention** — a hint that a member is internal, but it's still\nfully public and accessible. `#name` is **enforced** privacy — a SyntaxError to\naccess from outside.\n\n```js\nclass C {\n  _soft = 1     \u002F\u002F accessible: c._soft works (just \"please don't\")\n  #hard = 2     \u002F\u002F c.#hard -> SyntaxError\n}\n```\n\nPrefer `#private` for genuine encapsulation. The `_` convention persists in older\ncode and where subclass access is wanted (subclasses can't see `#private`).\n",{"id":49,"difficulty":25,"q":50,"a":51},"private-methods","Can methods be private?","Yes — prefix a method (or getter\u002Fsetter) with `#` to make it callable only from\nwithin the class.\n\n```js\nclass Service {\n  #validate(data) { return !!data }       \u002F\u002F private method\n  get #ready() { return this.#validate(this.data) }  \u002F\u002F private getter\n  submit(data) {\n    this.data = data\n    if (this.#validate(data)) { \u002F* ... *\u002F }\n  }\n}\n```\n\nPrivate methods keep internal helpers off the public API and prevent subclasses\nor callers from depending on them. They live per-class, not on the public\nprototype.\n",{"id":53,"difficulty":14,"q":54,"a":55},"static-private","Can static members be private?","Yes — combine `static` and `#` for private class-level fields and methods,\naccessible only inside the class.\n\n```js\nclass IdGenerator {\n  static #counter = 0\n  static #next() { return ++IdGenerator.#counter }\n  static create() { return { id: IdGenerator.#next() } }\n}\nIdGenerator.#counter   \u002F\u002F SyntaxError\n```\n\nStatic privates are great for internal class state (caches, counters,\nregistries) that shouldn't be touched from outside. Reference them via the class\nname inside the body.\n",{"id":57,"difficulty":14,"q":58,"a":59},"static-block","What is a static initialization block?","A `static { }` block (ES2022) runs once when the class is defined, for complex\nstatic setup that a field initializer can't express — and it can access private\nstatic members.\n\n```js\nclass Config {\n  static settings = {}\n  static {\n    const env = readEnv()             \u002F\u002F run setup logic\n    this.settings = parse(env)\n    this.#secret = deriveSecret(env)  \u002F\u002F can touch private statics\n  }\n  static #secret\n}\n```\n\nIt's the class equivalent of a one-time initializer, useful when static state\nneeds computation, multiple statements, or try\u002Fcatch at definition time.\n",{"id":61,"difficulty":14,"q":62,"a":63},"private-check","How do you check if an object has a private field (brand check)?","Use the `#field in obj` syntax (the \"ergonomic brand check\") — it returns whether\n`obj` has that private field, without throwing.\n\n```js\nclass Stream {\n  #buffer = []\n  static isStream(obj) { return #buffer in obj }\n}\nStream.isStream(new Stream())   \u002F\u002F true\nStream.isStream({})             \u002F\u002F false\n```\n\nThis is the reliable way to detect \"is this a real instance of my class\" — more\nrobust than `instanceof` (which can be spoofed via prototypes). Accessing\n`obj.#buffer` directly on a non-instance would throw, so the `in` form is used.\n",{"id":65,"difficulty":25,"q":66,"a":67},"encapsulation-benefits","Why is encapsulation with private fields valuable?","It hides internal state so callers can't depend on or corrupt it, letting you\nchange the implementation freely and enforce invariants in one place.\n\n```js\nclass Temperature {\n  #celsius = 0\n  set celsius(v) {\n    if (v \u003C -273.15) throw new RangeError('below absolute zero')\n    this.#celsius = v        \u002F\u002F validation can't be bypassed\n  }\n  get celsius() { return this.#celsius }\n}\n```\n\nWith public fields, anyone could set an invalid value directly. Private fields +\naccessors guarantee the validation runs and keep the public surface small and\nstable.\n",{"id":69,"difficulty":14,"q":70,"a":71},"private-inheritance","Are private fields inherited by subclasses?","No — `#private` fields are **not accessible** from subclasses. They belong\nstrictly to the class that declares them.\n\n```js\nclass Base { #secret = 1; getSecret() { return this.#secret } }\nclass Sub extends Base {\n  reveal() { return this.#secret }   \u002F\u002F SyntaxError — not visible\n}\n```\n\nThis is stricter than `protected` in other languages. For state subclasses need,\nuse the `_` convention or expose a protected-style accessor. Private fields are\ntruly class-local.\n",{"id":73,"difficulty":14,"q":74,"a":75},"static-inheritance","Are static members inherited?","Yes — subclasses inherit static methods and fields via the class's own prototype\nchain (`Sub.__proto__ === Base`).\n\n```js\nclass Base { static greet() { return 'hi' } }\nclass Sub extends Base {}\nSub.greet()   \u002F\u002F 'hi' — inherited static\n```\n\nInside an inherited static, `this` is the calling subclass, and `super` reaches\nthe parent's static. Static *fields* are inherited as references — careful, since\na shared static object is shared across the hierarchy.\n",{"id":77,"difficulty":25,"q":78,"a":79},"private-field-must-declare","Do you have to declare private fields before use?","Yes — every private field must be **declared in the class body**. You can't\ncreate one dynamically like a public property.\n\n```js\nclass C {\n  #x = 1            \u002F\u002F must declare\n  m() { this.#y = 2 }   \u002F\u002F SyntaxError — #y not declared\n}\n```\n\nThis is unlike public properties, which can be added anywhere. The requirement\nlets the engine know the full set of private fields at parse time (enabling the\nbrand check and strong encapsulation).\n",{"id":81,"difficulty":14,"q":82,"a":83},"singleton-static","How do you implement a singleton with static members?","Cache the instance in a private static field and expose it via a static getter\nor method, with a guarded\u002Fprivate constructor.\n\n```js\nclass Logger {\n  static #instance\n  static get instance() {\n    return Logger.#instance ??= new Logger()\n  }\n}\nLogger.instance === Logger.instance   \u002F\u002F true\n```\n\nThe private static `#instance` holds the single object; `??=` lazily creates it\nonce. (In JS, a module-level singleton is often simpler, but this is the\nclass-based form.)\n",{"id":85,"difficulty":25,"q":86,"a":87},"static-factory-vs-constructor","Why use static factory methods over constructors?","Static factories can have **descriptive names**, return cached\u002Fsubclass instances,\ndo async work indirectly, and offer multiple \"constructors\" — things a single\nconstructor can't.\n\n```js\nclass Color {\n  constructor(r, g, b) { \u002F* ... *\u002F }\n  static fromHex(hex) { \u002F* parse *\u002F return new Color(\u002F* ... *\u002F) }\n  static fromHSL(h, s, l) { \u002F* convert *\u002F return new Color(\u002F* ... *\u002F) }\n}\n```\n\nNamed factories (`fromHex`, `fromHSL`) read better than overloading one\nconstructor and let you control instance creation (caching, validation). A widely\nused OOP idiom.\n",{"id":89,"difficulty":25,"q":90,"a":91},"private-getter-setter","Can you have private getters and setters?","Yes — `get #name()` \u002F `set #name(v)` define private accessors, usable only inside\nthe class for computed private values.\n\n```js\nclass Box {\n  #w = 0; #h = 0\n  get #area() { return this.#w * this.#h }   \u002F\u002F private computed value\n  report() { return `area: ${this.#area}` }\n}\n```\n\nPrivate accessors are handy for internal derived values you don't want to expose\nor recompute manually. Like all `#` members, they're inaccessible and invisible\noutside the class.\n",{"id":93,"difficulty":14,"q":94,"a":95},"weakmap-privacy","How was privacy done before","With closures (per-instance functions) or a module-scoped **`WeakMap`** keyed by\ninstance — both hide data from outside the class.\n\n```js\nconst _balance = new WeakMap()\nclass Account {\n  constructor() { _balance.set(this, 0) }\n  deposit(n) { _balance.set(this, _balance.get(this) + n) }\n  get balance() { return _balance.get(this) }\n}\n```\n\nThe `WeakMap` lives in module scope, so only the class's methods can read it, and\nentries are garbage-collected with the instance. `#private` fields now do this\nnatively and more cleanly.\n",{"id":97,"difficulty":25,"q":98,"a":99},"static-vs-module","When should you use a static method vs a module function?","Use a **static method** when the function is conceptually tied to the class\n(factories, class-specific helpers, polymorphic via `this`). Use a **plain module\nfunction** for standalone utilities not bound to a class.\n\n```js\n\u002F\u002F tied to the class -> static\nclass Vector { static add(a, b) { \u002F* ... *\u002F } }\n\u002F\u002F generic utility -> module function\nexport function clamp(n, lo, hi) { \u002F* ... *\u002F }\n```\n\nDon't create a class full of only static methods just to namespace functions — a\nmodule is the idiomatic JS namespace. Statics belong with classes that also have\ninstances.\n",{"id":101,"difficulty":25,"q":102,"a":103},"private-method-vs-closure","What is the advantage of a private method over a closure helper?","A `#private` method lives on the class **once** (shared), whereas a closure helper\ndefined per instance (or inside the constructor) is duplicated per object. Private\nmethods give encapsulation **and** memory efficiency.\n\n```js\nclass Service {\n  #parse(x) { \u002F* shared across instances *\u002F }   \u002F\u002F one definition\n}\n\u002F\u002F vs a per-instance closure in the constructor (one function per object)\n```\n\nSo `#private` methods are usually better than closure-based privacy for classes:\nsame hiding, no per-instance function cost.\n",{"id":105,"difficulty":25,"q":106,"a":107},"enum-pattern","How do you create enum-like constants with static members?","Use static fields (often on a frozen class) to model a fixed set of named\nconstants.\n\n```js\nclass Direction {\n  static North = new Direction('N')\n  static South = new Direction('S')\n  constructor(code) { this.code = code }\n}\nObject.freeze(Direction)\nDirection.North.code   \u002F\u002F 'N'\n```\n\nJavaScript has no native `enum`, so frozen static instances (or a frozen plain\nobject `Object.freeze({ North: 'N', ... })`) are the common patterns for\nenumerations.\n",{"id":109,"difficulty":14,"q":110,"a":111},"static-this-pitfall","What is a common pitfall referencing static fields?","Inside an **instance** method, `this` is the instance, so `this.staticField` is\n`undefined` — you must use the class name (or `this.constructor`).\n\n```js\nclass C {\n  static MAX = 10\n  check(n) {\n    return n \u003C this.MAX            \u002F\u002F undefined — MAX is static\n    \u002F\u002F return n \u003C C.MAX            \u002F\u002F\n    \u002F\u002F return n \u003C this.constructor.MAX  \u002F\u002F subclass-aware\n  }\n}\n```\n\nUse `ClassName.field` for a fixed reference, or `this.constructor.field` if you\nwant subclasses to be able to override the static value.\n",{"id":113,"difficulty":14,"q":114,"a":115},"private-in-operator-guard","Why does accessing a private field on the wrong object throw?","Private fields are \"branded\" to their class. Reading `obj.#field` on an object\nthat isn't an instance throws a `TypeError`, which protects encapsulation but\nmeans you should guard with `#field in obj` first.\n\n```js\nclass A { #x = 1; static read(o) { return #x in o ? o.#x : null } }\nA.read(new A())   \u002F\u002F 1\nA.read({})        \u002F\u002F null (guarded; direct o.#x would throw)\n```\n\nThe throw-on-mismatch behavior is what makes `#field in obj` the safe brand\ncheck, and prevents one class's private accessor from working on foreign objects.\n",{"id":117,"difficulty":25,"q":118,"a":119},"freeze-class","How do you make a class's static configuration immutable?","Freeze the class (and\u002For its static objects) so static fields can't be reassigned\nafter definition.\n\n```js\nclass Config {\n  static API = '\u002Fv1'\n  static TIMEOUT = 5000\n}\nObject.freeze(Config)\nConfig.API = '\u002Fv2'   \u002F\u002F ignored (throws in strict mode)\n```\n\n`Object.freeze(Config)` locks top-level static props; nested static objects need\ntheir own freeze (it's shallow). A `static {}` block plus `Object.freeze` is a\nclean way to set up immutable class-level config.\n",null,{"description":11},"JavaScript static and private class member interview questions — static methods and fields, private fields and methods, static blocks, and encapsulation patterns.","javascript\u002Fclasses\u002Fstatic-private","Static & Private Members","Classes & OOP","classes","2026-06-18","J6BpWyoml9KkWfwfDsQHBLHqJm6SUDbQqoQYjj8Gipc",[130,134,137,138],{"subtopic":131,"path":132,"order":133},"Class Syntax & Methods","\u002Fjavascript\u002Fclasses\u002Fclass-syntax",1,{"subtopic":135,"path":136,"order":12},"Inheritance with extends & super","\u002Fjavascript\u002Fclasses\u002Fclass-inheritance",{"subtopic":124,"path":21,"order":20},{"subtopic":139,"path":140,"order":141},"Mixins & Composition","\u002Fjavascript\u002Fclasses\u002Fmixins-composition",4,{"path":143,"title":144},"\u002Fblog\u002Fjavascript-static-private-class-members","JavaScript Static & Private Class Members — Fields, Methods, and True Encapsulation",1781808676232]