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?
In JavaScript my practice has been to avoid constants as much as I can and use strings instead. Problems with constants appear when you want to expose your constants to the outside world:
For example one could implement the following Date API:
But it's much shorter and more natural to simply write:
This way "days" and "hours" really act like constants, because you can't change from the outside how many seconds "hours" represents. But it's easy to overwrite
MyModule.Date.HOUR
.This kind of approach will also aid in debugging. If Firebug tells you
action === 18
it's pretty hard to figure out what it means, but when you seeaction === "save"
then it's immediately clear.In JavaScript, my preference is to use functions to return constant values.
I use
const
instead ofvar
in my Greasemonkey scripts, but it is because they will run only on Firefox...Name convention can be indeed the way to go, too (I do both!).
If it is worth mentioning, you can define constants in angular using
$provide.constant()
The keyword 'const' was proposed earlier and now it has been officially included in ES6. By using the const keyword, you can pass a value/string that will act as an immutable string.
Are you trying to protect the variables against modification? If so, then you can use a module pattern:
Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.
If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.