Is there a way to define symbolic constants in Javascript?

I searched if JavaScript offers an average for defining symbolic constants, but found nothing. Did I miss something?

Is it common practice to use const var instead?

var const MAXIMUM_VALUE = 100; 

Thanx.

+3
source share
3 answers

const IE is not supported, therefore, if you want to support IE, which is out of the question.

, , , - , - ALL UPPERCASE. , , . , :

function myConst() { return 'myValue'; }

, , , , .

:

+7

. var. const var.

const MAXIMUM_VALUE = 100;
+3
Object.defineProperty(window, 'CONSTANT_NAME', {value: CONSTANT_VALUE});

// usage
console.log(CONSTANT_NAME);

Object.defineProperty() :

  • configurable true, . false.

  • enumerabletrue if and only if this property appears while enumerating the properties of the corresponding object. The default is false.

  • writabletrue if and only if the value associated with the property can be changed using the assignment operator. The default is false.

if "constant" is an object that you might want to make it immutable by freezing it. obj = Object.freeze(obj). keep in mind that child-property objects will not be automatically frozen.

+2
source

Source: https://habr.com/ru/post/1705423/


All Articles