Is there a way to use constants in JavaScript?
If not, what's the common practice for specifying variables that are used as constants?
Is there a way to use constants in JavaScript?
If not, what's the common practice for specifying variables that are used as constants?
If you don't mind using functions:
This approach gives you functions instead of regular variables, but it guarantees* that no one can alter the value once it's set.
I personally find this rather pleasant, specially after having gotten used to this pattern from knockout observables.
*Unless someone redefined the function
constant
before you called itYet there is no exact cross browser predefined way to do it , you can achieve it by controlling the scope of variables as showed on other answers.
But i will suggest to use name space to distinguish from other variables. this will reduce the chance of collision to minimum from other variables.
Proper namespacing like
so while using it will be
iw_constant.name
oriw_constant.age
You can also block adding any new key or changing any key inside iw_constant using Object.freeze method. However its not supported on legacy browser.
ex:
For older browser you can use polyfill for freeze method.
If you are ok with calling function following is best cross browser way to define constant. Scoping your object within a self executing function and returning a get function for your constants ex:
//to get the value use
iw_constant('name')
oriw_constant('age')
** In both example you have to be very careful on name spacing so that your object or function shouldn't be replaced through other library.(If object or function itself wil be replaced your whole constant will go)
An improved version of Burke's answer that lets you do
CONFIG.MY_CONST
instead ofCONFIG.get('MY_CONST')
.It requires IE9+ or a real web browser.
* The properties are read-only, only if the initial values are immutable.
The
const
keyword is in the ECMAScript 6 draft but it thus far only enjoys a smattering of browser support: http://kangax.github.io/compat-table/es6/. The syntax is:Since ES2015, JavaScript has a notion of
const
:This will work in pretty much all browsers except IE 8, 9 and 10. Some may also need strict mode enabled.
You can use
var
with conventions like ALL_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code:No, not in general. Firefox implements
const
but I know IE doesn't.@John points to a common naming practice for consts that has been used for years in other languages, I see no reason why you couldn't use that. Of course that doesn't mean someone will not write over the variable's value anyway. :)