Lesson 66 +15 XP

Static Methods

Static Methods

Static methods belong to the class itself, not to individual objects.

Defining a static method

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

Calling a static method

MathHelper.add(2, 3); // 5

You call it on the class name, not on an instance.

Why use static methods?

  • Utility functions that do not need instance data.
  • Helper functions grouped with a related class.
  • Factory methods that create instances.

Static vs instance

  • Instance methods: need an object, use this, called like obj.method().
  • Static methods: called on the class, like Class.method().
class Person {
  constructor(name) { this.name = name; }
  hello() { return "Hi " + this.name; }  // instance
  static create(name) { return new Person(name); } // static
}

const p = Person.create("Ada"); // static call
p.hello(); // instance call

TL;DR

  • Static methods belong to the class.
  • Call them with ClassName.method().
  • Use them for utilities and helpers.
  • They have no this bound to an instance.