ES6 static class constants?

Hi guys,

this is totally newbieish, BUT how do you guys define class constants in ES6?

… something like this would be nice & clean: (but throws errors)

class Tester {
  CONSTANT = 'a value';  // this throws an error

  do() {

1 Like

contants like such:

const CONSTANT = 'a value';


class Tester {
    static get CONSTANT() {
      return 'a value';

I also find this pretty annoying. You have to declare constants outside the class or attach them to the class later.

class Tester {
  do () {

Tester.CONSTANT = 'foo';

Yeahhh - thats the one… and it is ugly as hell!!!
It makes me think about switching to CoffeeScript again. :smile:
But at least we can do something like:

// Namespace
Ns = {}

Ns.Tester = class Tester {
  static get CONSTANT_1() { return 'ohaa1'; }
  static get CONSTANT_2() { return 'ohaa2'; }
  static get CONSTANT_3() { return 'ohaa3'; }

  constructor() {

Well… you can’t do this in ES6 but you can do it in ES7 if you’re ok living on the edge. It’s under the Babel stage 0 flag aka ‘experimental’. Otherwise static properties have to be defined as @mnmtanish mentioned.

Example in Babel REPL

Hi @SkinnyGeek1010: thanks for the hint. But I really think it’s not too good to live “on the edge”. Hehe…

OK guys, so just out of intereset, which one do we pick?

Option 1:

Option 2:

I think I will stick with Option 1. :smile:
… or switch to Coffescript… someday. :smile:

What’s the use case for class constants in JS ?