I'm designing some classes and for some data I want to use fields that are constant.
Now, AS USUAL, IE does not support the key const so
const T = 10;
not work.
I could create a property via __defineGetter__
and __defineSetter__
to mime that but
, AS USUAL, IE does not support that syntax (IE 8 has Object.defineProperty
but not work on custom object).
Any idea?
ES6 provides a new way of declaring a constant by using the const keyword. The const keyword creates a read-only reference to a value. By convention, the constant identifiers are in uppercase. Like the let keyword, the const keyword declares blocked-scope variables.
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
Constants are immutable variables which value cannot be changed. Once, you have created a constant, its value cannot be changed. While coding in JavaScript, many times you may have come across a requirement to create constants.
The const keyword was introduced in ES6 (2015). Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned. Variables defined with const have Block Scope.
Old question but nowadays you can simply use:
const MY_CONST = 10;
From MDN:
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
Supported by all the main browsers already.
There is a freeze() method in Javascript which can be used to create actual constants.
Usage:
var consts = {}; // Object to store all constants
consts.MY_CONSTANT= 6;
Object.freeze(consts); // Make the consts truly read only
consts.MY_CONSTANT= 7; // Trying to do this will give error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With