0

What would be the preferred way to create constants in javascript, specifically with ES6?

Currently I have a constants class which has methods that return the string I'm looking for.

 class Constants {
    constructor() {}

    SOMECONSTANT() {
       return 'someconstant';
    }
 }
Beanwah
  • 103
  • 3
  • 1
    see [Are there any OO-principles that are practically applicable for Javascript?](http://programmers.stackexchange.com/a/180588/31260) – gnat May 28 '15 at 19:23

1 Answers1

1

For backwards compatibility, I would create a read-only property of the encapsulating object, which could be the global object:

Object.defineProperty(this, 'CONST', {
  value: 123,
  writable: false
});

See: Object.defineProperty - writable attribute

Otherwise, ES6 has a const keyword.

const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];

See const.

svidgen
  • 13,414
  • 2
  • 34
  • 60