Skip to content

JavaScript class constants | Example code

  • by

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

JavaScript class constants

A 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading