Static Properties & Methods

Static members belong to the class itself, not to any individual object created from it. They're shared across everything.

What Is a Static Member?

Normally, methods and properties on a class belong to each instance (each object you create with new). A static method or property belongs to the class itself. You call it directly on the class name, not on an instance.

🏫 Real-life analogy

Think of a school. Each student (instance) has their own name, grade, and locker. But the school's total student count and the school name belong to the school itself β€” not to any individual student. Static members are like the school's own data and tools.

Static Methods

A static method is a function on the class that you call on the class name itself β€” not on an object made from the class.

class MathHelper {
  static square(n) {
    return n * n;
  }

  static cube(n) {
    return n * n * n;
  }

  static add(a, b) {
    return a + b;
  }
}

// Called on the CLASS β€” not on an instance
MathHelper.square(4); // 16
MathHelper.cube(3);   // 27
MathHelper.add(2, 3); // 5

// ❌ Cannot call on an instance
const m = new MathHelper();
m.square(4); // TypeError: m.square is not a function
  • static keyword before the method name makes it static
  • You call it on the class: MathHelper.square(4)
  • You cannot call it on an object: new MathHelper().square(4) throws an error
  • Static methods are great for utility functions that relate to the class but don't need object data

Static Properties (Fields)

Static properties store values that belong to the class, not to any instance. All instances share the same static property.

class Counter {
  static count = 0; // shared across ALL Counter objects

  constructor(name) {
    this.name = name;
    Counter.count++; // increment the class-level counter each time
  }
}

const a = new Counter("Alice");
const b = new Counter("Bob");
const c = new Counter("Carol");

Counter.count; // 3 β€” the class knows how many instances were made
a.count;       // undefined β€” instances don't have access to static properties
  • static count = 0 β€” a property that lives on the class itself
  • Counter.count++ β€” we access it via the class name, not this
  • All three instances update the same count β€” it's shared
  • Individual instances (a, b, c) cannot read static properties directly
πŸ“Œ Static fields support (ES2022)

The static field = value syntax (inside the class body) was added in ES2022. All modern browsers support it. An older way to do the same thing is: Counter.count = 0; written after the class definition β€” this works everywhere.

Static vs Instance β€” Side by Side

FeatureInstance memberStatic member
Belongs toEach object (new Dog())The class itself (Dog)
How to callrex.bark()Dog.create()
Access thisYes β€” refers to the instanceNo β€” this refers to the class
Shared across instances?No β€” each object has its own copyYes β€” one value for the whole class
Typical useObject behavior (bark, eat, save)Utilities, factories, counters, constants

Real-World Use Cases

1. Factory Methods β€” Creating Objects in Different Ways

A factory method is a static method that creates and returns an instance. It's handy when you want different ways to build an object.

class User {
  constructor(name, role) {
    this.name = name;
    this.role = role;
  }

  static createAdmin(name) {
    return new User(name, "admin"); // creates a User with role already set
  }

  static createGuest() {
    return new User("Guest", "guest");
  }
}

const admin = User.createAdmin("Alice");
const guest = User.createGuest();

admin.name; // "Alice"
admin.role; // "admin"
guest.role; // "guest"

2. Constants on a Class

Static properties are great for constants that are naturally related to the class.

class Direction {
  static UP    = "up";
  static DOWN  = "down";
  static LEFT  = "left";
  static RIGHT = "right";
}

Direction.UP;    // "up"
Direction.RIGHT; // "right"

// Use them instead of raw strings β€” avoids typos
function move(dir) {
  if (dir === Direction.UP) { /* move up */ }
}

3. Validation Helper

class Email {
  constructor(address) {
    if (!Email.isValid(address)) {
      throw new Error("Invalid email address");
    }
    this.address = address;
  }

  static isValid(address) {
    return address.includes("@") && address.includes(".");
  }
}

Email.isValid("hello@example.com"); // true  β€” check without creating an object
Email.isValid("notanemail");         // false

const e = new Email("hello@example.com"); // works
const bad = new Email("notanemail");       // throws Error

Static Members and Inheritance

Child classes inherit static methods from parent classes β€” you can call the parent's static method on the child class too.

class Animal {
  static kingdom = "Animalia";

  static describe() {
    return `Kingdom: ${this.kingdom}`;
    // here 'this' is the class itself, not an instance
  }
}

class Dog extends Animal {
  static species = "Canis lupus familiaris";
}

Animal.describe();  // "Kingdom: Animalia"
Dog.describe();     // "Kingdom: Animalia" ← inherited!
Dog.kingdom;        // "Animalia"         ← static property inherited too
Dog.species;        // "Canis lupus familiaris" ← Dog's own static
πŸ’‘ this inside a static method

Inside a static method, this refers to the class itself (not an instance). So this.kingdom inside Animal.describe() means Animal.kingdom. When called on Dog, this becomes Dog.

You Already Know Static Members

JavaScript's built-in classes use static methods everywhere. You've likely already used them:

// Math class β€” all static methods
Math.round(4.7);  // 5
Math.max(1, 2, 3); // 3
Math.PI;          // 3.14159… (static property)

// Array β€” static methods
Array.isArray([1, 2]);    // true
Array.from("hello");      // ["h","e","l","l","o"]
Array.of(1, 2, 3);        // [1, 2, 3]

// Object β€” static methods
Object.keys({ a: 1 });    // ["a"]
Object.freeze({ a: 1 });  // frozen object

// Number β€” static methods and properties
Number.isInteger(4);      // true
Number.isNaN(NaN);         // true
Number.MAX_SAFE_INTEGER;    // 9007199254740991

// Promise β€” static methods
Promise.resolve(42);
Promise.all([p1, p2]);

All of these β€” Math.round, Array.isArray, Object.keys β€” are static methods. You call them on the class name, not on an instance.

Common Mistakes

⚠ Watch out for
  • Calling a static method on an instance: const m = new MathHelper(); m.square(3) β€” this throws a TypeError. Static methods live on the class, not instances.
  • Using this to refer to instance data inside a static method: Static methods don't have access to instance properties. Inside a static method, this is the class, not an object.
  • Mutating a static property from an instance: Writing this.count++ inside an instance method will create an instance property count, not change the static one. Always use ClassName.count++.
class Foo {
  static total = 0;

  constructor() {
    this.total++;  // ❌ creates instance.total = NaN, doesn't change Foo.total
    Foo.total++;   // βœ… correct β€” updates the class-level property
  }
}

Best Practices

  • Use static methods for utility/helper functions that are logically grouped with the class but don't need to read or write instance data.
  • Use static properties for constants, configuration, and counters that belong to the concept of the class, not any one object.
  • Factory methods (User.createAdmin()) are a great use for static β€” they make your API cleaner and more readable.
  • Always access static members via the class name (ClassName.prop), not via this in an instance method β€” it's clearer and avoids bugs.

Performance Notes

Static methods are slightly cheaper than instance methods because they're looked up directly on the class, not through the prototype chain. In practice this difference is tiny β€” the main benefit of static is code organisation, not speed.

Browser Compatibility

Static methods have been supported since ES6 (2015) in all browsers. Static fields (static prop = value inside the class body) are ES2022 and supported in all modern browsers since 2022. For older environments, declare static properties after the class: MyClass.prop = value;.

Interview Questions

What is a static method?

A static method is a method that belongs to the class itself, not to any instance created from it. You call it on the class name: ClassName.method(). It doesn't have access to instance properties β€” this inside a static method refers to the class itself.

When should you use a static method vs an instance method?

Use a static method when the functionality is related to the class as a concept but doesn't need to read or modify any particular object's data. Utilities, factory methods, validators, and constants are good candidates. Use an instance method when the behavior needs to work with the specific object's own data.

Can a child class access a parent's static method?

Yes. Static methods are inherited. If Dog extends Animal and Animal has a static method create(), you can call Dog.create() too.

✏️ Exercise

Create a Temperature class with static methods celsiusToFahrenheit(c) and fahrenheitToCelsius(f). No constructor needed β€” these are pure utility methods.

🧠 Quiz

1. How do you call a static method named run on a class called Task?

Task.run() β€” on the class name, not on an instance.

2. Inside a static method, what does this refer to?

The class itself, not an instance.

3. Name two built-in JavaScript static methods you already use.

Math.round(), Array.isArray(), Object.keys(), Number.isNaN(), Promise.all() β€” any two of these (or many others).

πŸš€ Mini Challenge

Create a Validator class with at least three static methods: isEmail(str), isPositiveNumber(n), and isNonEmptyString(str). Each should return true or false. No instances should ever need to be created from this class.

Summary

  • The static keyword makes a method or property belong to the class itself, not to instances.
  • Static methods are called on the class: ClassName.method().
  • Static properties store shared data or constants at the class level.
  • Inside a static method, this refers to the class, not an instance.
  • Child classes inherit static members from parent classes.
  • You already use static members every day: Math.round, Array.isArray, Object.keys.

Related Topics

MDN reference: developer.mozilla.org β†’ JavaScript β†’ Classes β†’ static

vvv