Skip to content

JavaScript class constants | Example code

  • by

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

JavaScript class constants

Simple example code declares constants outside the class and adds getters that return the constants in our class.

<!DOCTYPE html>
<html>
<body>
  <script>
    const const1 = 100,
    const2 = 200;

    class Test {
      static get constant1() {
        return const1;
      }  
      static get constant2() {
        return const2;
      }
    }

    console.log(Test.constant1)
    console.log(Test.constant2)
  </script>
</body>
</html>

Output:

JavaScript class constants

Define a const in the class constructor (ES6)

You use static read-only properties to declare constant values that are scoped to a class.

class Foo {
    static get BAR() {
        return 42;
    }
}

console.log(Foo.BAR); // print 42.
Foo.BAR = 43; // triggers an error

Do comment if you have any doubts or suggestions on this Js class topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *