CodeBlanks Logo Icon CodeBlanks

static members

JavaScript course · Advanced · Lesson 11/100

Learn class-level methods and properties with static.

What is static?

When you write static before a member, it belongs to the class itself, not instances. You access it through the class name, not through an instance.

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

You call these members as MathHelper.PI or MathHelper.square(4).

Static vs instance members

Static members are called on the class name; instance members are called on an instance. They serve different purposes.

MathHelper.square(4);  // static call
const m = new MathHelper();
m.square(4);            // wrong: not via instance

Helper operations (math, conversion) are usually static; methods that need instance data stay as instance methods.

Exercise MathHelper class

Declare a MathHelper class. Add a static PI property set to 3.14. Add a static square(n) method that returns n * n.

Show example solution
First write static PI = 3.14, then static square(n) { return n * n; }.
Example solution:
class MathHelper {
  static PI = 3.14;
  static square(n) {
    return n * n;
  }
}

Test yourself

  1. How do you access a static method?

    MathHelper.square(4)
    • through an instance
    • through the class name
    • through this
    • by method name
    Show answer

    through the class name — Correct! Static methods are called on the class name.

  2. Call the static method

    const area = ____;
    Show answer
    const area = MathHelper.square(4);
  3. Match the concepts

    static
    declares a class-level member
    ClassName.method()
    static method call
    this.method()
    instance method call
    static PI
    class-level constant

All lessons in Advanced