DEV Community

Cory Rylan
Cory Rylan

Posted on • Originally published at coryrylan.com

Using Static Keyword in JavaScript

This post, we will learn how the static keyword works in JavaScript.
First, let's take a look at a simple JavaScript Class.

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  greet() {
    console.log(`Hello, ${this.firstName} ${this.lastName}`);
  }
}

const person = new Person('Cory', 'Rylan');
person.greet(); // Hello, Cory Rylan

const person = new Person('John', 'Doe');
person.greet(); // Hello, John Doe
Enter fullscreen mode Exit fullscreen mode

With JavaScript Classes, we can add methods and properties that can be accessed per instance of the Class. This is standard behavior when you make multiple instances of a Class. If we create a method that does not access an instance property, we can use the static keyword.

class MathUtils {
  static add(num, num2) {
    return num + num2;
  }

  static subtract(num, num2) {
    return num - num2;
  }
}

// Static Methods
console.log(MathUtils.add(1, 2)); // 3

// Cannot access static values on instance
const instance = new MathUtils();
instance.add() // error undefined
Enter fullscreen mode Exit fullscreen mode

When creating a static method, it can only be accessed on the Class definition itself. If you try to access the method on an instance, it will fail. Static methods are useful for utility methods that do not contain any state. One could argue that if you have static methods, you could refactor them to be plain functions instead.

You can also use the static keyword on properties and getters.

class MathUtils {
  static value = '';
}

// Static Properties
MathUtils.value = 'Hello from static property';
console.log(MathUtils.value);
Enter fullscreen mode Exit fullscreen mode

When using static properties, you can access them and set them any time, but they exist only on the Class itself and are not accessible to any instance of the Class. Along with static properties, you can create static getters.

class MathUtils {
  static get random() {
    return Math.random();
  }
}

// Static Getter
console.log(MathUtils.random, MathUtils.random); // two different values
Enter fullscreen mode Exit fullscreen mode

Static getters allow you to compute values on the fly with a property.
For this example, we return a new value anytime we access the random property.

Check out the full working demo!

Top comments (9)

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I find it funny that you can now do.

class MyClass{
    static void main () {

    }
}

Reminds me of old school college IT lessons.

Collapse
 
stemmlerjs profile image
Khalil Stemmler

Ah the good 'ol days

Collapse
 
evanplaice profile image
Evan Plaice

The best part... you will never need to type that out again.

Collapse
 
seanmclem profile image
Seanmclem

In you're last example, you use 'get' in addition to static. What does that really do? I've seen it a lot and used it a little, but how does it make random() different from a function returns what random(( is already returning

Collapse
 
devhammed profile image
Hammed Oyedele

Without the static, you have to instantiate the class before you will be able to access the getter.

Collapse
 
seanmclem profile image
Seanmclem

right. I was asking about what the getter is doing in-general. I'm sure it's something, but what?

Thread Thread
 
stemmlerjs profile image
Khalil Stemmler

The getter is just another syntactic-sugar to reach into objects. It's equivalent to using the dot notation like person.name but it provides the ability for you to:

  • watch when objects are being accessed (in general, this is how Vue.js detects changes)
  • dynamically create return objects

It enables you to do both of those without changing the syntax.

Thread Thread
 
devhammed profile image
Hammed Oyedele

Getters are usually used to create dynamic properties because it is a function you can write logic e.g you can read value of a property from a file or from database.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

It might just be better to create an object straight up in that instance.