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:
date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)
But it's much shorter and more natural to simply write:
date.add(5, "days").add(12, "hours")
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 see action === "save"
then it's immediately clear.