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?
with the "new" Object api you can do something like this:
take a look at this on the Mozilla MDN for more specifics. It's not a first level variable, as it is attached to an object, but if you have a scope, anything, you can attach it to that.
this
should work as well. So for example doing this in the global scope will declare a pseudo constant value on the window (which is a really bad idea, you shouldn't declare global vars carelessly)note: assignment will give you back the assigned value in the console, but the variable's value will not change
Another alternative is something like:
Then simply:
var foo = constantMap.MY_CONSTANT
If you were to
constantMap.MY_CONSTANT = "bar"
it would have no effect as we're trying to use an assignment operator with a getter, henceconstantMap.MY_CONSTANT === "myconstant"
would remain true.Group constants into structures where possible:
Example, in my current game project, I have used below:
Assignment:
Comparision:
More recently I am using, for comparision:
IE11 is with new ES6 standard that has 'const' declaration.
Above works in earlier browsers like IE8, IE9 & IE10.
Clearly this shows the need for a standardized cross-browser const keyword.
But for now:
or
Both seem sufficient and anything else is like shooting a fly with a bazooka.
in Javascript already exists constants. You define a constant like this:
This cannot change through reassignment.
ECMAScript 5 does introduce
Object.defineProperty
:It's supported in every modern browser (as well as IE ≥ 9).
See also: Object.defineProperty in ES5?