circuit

How to Declare Static Constants in ES6 Classes?




Photo by Daan Stevens on Unsplash

Photo by Daan Stevens on Unsplash

Sometimes, we may want to declare static constants in our JavaScript classes.

In this article, we'll look at how to declare static constants in ES6 classes.

Add Getters in Our Class

To declare static constants in our ES6 classes, we can declare constants outside the class and add getters that return the constants in our class.

For instance, we can write:

const constant1 = 3,
  constant2 = 2;
class Example {
  static get constant1() {
    return constant1;
  }

  static get constant2() {
    return constant2;
  }
}

console.log(Example.constant1)
console.log(Example.constant2)

We declare constant1 and constant2 .

Then in the Example class, we create the constant1 and constant2 getters.

We add the static keyword before get so that we can make the static.

Then in the getter function, we return the constant1 and constant2 values respectively.

Likewise, we can write:

class Example {
  static get constant1() {
    return 3
  }

  static get constant2() {
    return 2
  }
}

Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

which is equivalent to what we have written above.

So when we log the values of Example.constant1 and Example.constant2 , we see 3 and 2 respectively.

Object.freeze

We can freeze the class to make the whole class immutable.

To do this, we write:

class Example {}
Example.constant1 = 3
Example.constant2 = 2
Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

We add our static properties with:

Example.constant1 = 3
Example.constant2 = 2

This works since classes are constructor functions, which are objects.

This also means we can use the Object.freeze method on Example to make the Example class immutable.

So we can log the values of the Example.constant1 and Example.constant2 properties and get their values.

We should see 3 and 2 respectively.

Conclusion

We can declare static constants in our JavaScript class by declaring static getters that returns constants declared outside the class.

Also, we can freeze the class with the Object.freeze method since it's a regular object.

This makes the class immutable.




Continue Learning