Static Class Methods in JavaScript

Level 4160 keystrokes

Defines static methods that can be called directly on the class without creating an instance.

JavaScript code

// class defines a blueprint for creating objects
1class MathHelper {
// static makes the method belong to the class itself, not to its instances
2 static square(x) {
// Returns x multiplied by itself
3 return x * x;
4 }
// Another static method for calculating cube
5 static cube(x) {
// Returns x cubed (x * x * x)
6 return x * x * x;
7 }
8}
// Call static methods directly on the class name
// No need to use 'new MathHelper()'
9console.log(MathHelper.square(4));
10console.log(MathHelper.cube(3));

Output

16
27
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 6
  • )× 6
  • ;× 4
  • .× 4
  • {× 3
  • }× 3
  • *× 3

More JavaScript examples at level 4

← JavaScript typing practice