Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

static

A method or property of the class itself, not of its objects.

Available since: ES2015

Syntax

static method() { … } / static field = value

Examples

A static method — an object factory:

class User {
  constructor(name, role) {
    this.name = name;
    this.role = role;
  }
 
  static admin(name) {
    return new User(name, 'admin');
  }
}
 
console.log(User.admin('Anna').role);

Output:

admin

A static field — a shared counter:

class Ticket {
  static count = 0;
 
  constructor() {
    Ticket.count++;
    this.number = Ticket.count;
  }
}
 
new Ticket();
const second = new Ticket();
 
console.log(second.number, Ticket.count);

Output:

2 2

Notes

Static members are called through the class name: User.admin(). On an object anna.admin is undefined. Built-in examples are Math.max(), Array.from(), Object.keys().

See also

  • class — Declares a class — a template for objects with shared methods.
  • Private fields (#) — Fields and methods accessible only inside the class.

In the tutorial

  • Private and static members — Private fields and methods of JavaScript classes with #, encapsulation, static methods and properties.

Thanks for reading!

Donate to the site — we work hard for you.