iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Class Static

static members belong to the class itself, not to instances. They're useful for factories, constants, and utility methods that don't need an instance to work.

Static methods, fields, and blocks

JS
class User {
  // Static field — shared by everyone
  static count = 0;

  // Static block — runs once when the class is defined
  static {
    User.MAX_NAME_LEN = 60;
  }

  constructor(name) {
    this.name = name;
    User.count++;
  }

  // Static factory
  static fromJSON(text) {
    const { name } = JSON.parse(text);
    return new User(name);
  }

  // Static utility
  static isValidName(name) {
    return typeof name === "string" && name.length < User.MAX_NAME_LEN;
  }
}

new User("Ada");
new User("Grace");

User.count;                           // 2
User.fromJSON('{"name":"Linus"}');    // User { name: "Linus" }
User.isValidName("");                 // true (technically) — adjust as needed

How to call

  • Always call on the class: User.fromJSON(…).
  • Never on an instance: u.fromJSON is undefined.
  • Inside another static, refer to siblings via the class name or this (the class itself).

When static earns its keep

PatternExample
FactoryDate.now(), Array.from(), Promise.resolve()
Type testArray.isArray(x), Number.isFinite(x)
Constant groupingMath.PI, Number.MAX_SAFE_INTEGER
Instance counterShared registries or pools.
Tip: If a method doesn't use this, it probably wants to be static — or just a plain module-level function.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Class Static!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Mark this factory as belonging to the class itself.

class User { fromJSON(text) { return new User(JSON.parse(text).name); } }

Test yourself

Q1. Call `User.fromJSON(text)` on…
Q2. Static blocks run…
Q3. If a method does not use `this`, it could be…

Discussion

Loading…