Skip to the content

Static methods

JavaScript · Unit 12: Classes and objects

You've already used a method that's called with the class name and not with an object: Object.keys(obj). It's a static method: it belongs to the class, not to each object.

You write it with static in front and use it without new.

class Temp {
  static toF(c) {
    return c * 9 / 5 + 32;
  }
}
console.log(Temp.toF(20));
console.log(Temp.toF(100));

Prints

68
212

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank to convert 30 °C to Fahrenheit.

  3. 3. Put the lines in order

    Put in order the program that adds 8% sales tax to a price of 100.

  4. 4. Find the bug

    This program should print 12, the area of the rectangle. Which line has the bug?

  5. 5. Multiple choice

    In a Student class, which of these methods makes the most sense as static?

  6. 6. Find the bug

    This program should print 77, today's 25 °C in Fahrenheit. Which line has the bug?

  7. 7. Predict the output

    Something the example did is missing here. What does it print?

  8. 8. Complete the code

    fromMinutes creates a Clock from minutes: 135 is 2 hours and 15 minutes. Fill in the blank so it prints "2 15".

  9. 9. Predict the output

    The shopping list arrives as text. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →