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?
You can easily equip your script with a mechanism for constants that can be set but not altered. An attempt to alter them will generate an error.
Forget IE and use the
const
keyword.Introducing constants into JavaScript is at best a hack.
A nice way of making persistent and globally accessible values in JavaScript would be declaring an object literal with some "read-only" properties like this:
you'll have all your constants grouped in one single "my" accessory object where you can look for your stored values or anything else you may have decided to put there for that matter. Now let's test if it works:
As we can see, the "my.constant1" property has preserved its original value. You've made yourself some nice 'green' temporary constants...
But of course this will only guard you from accidentally modifying, altering, nullifying, or emptying your property constant value with a direct access as in the given example.
Otherwise I still think that constants are for dummies. And I still think that exchanging your great freedom for a small corner of deceptive security is the worst trade possible.
Okay, this is ugly, but it gives me a constant in Firefox and Chromium, an inconstant constant (WTF?) in Safari and Opera, and a variable in IE.
Of course eval() is evil, but without it, IE throws an error, preventing scripts from running.
Safari and Opera support the const keyword, but you can change the const's value.
In this example, server-side code is writing JavaScript to the page, replacing {0} with a value.
What is this good for? Not much, since it's not cross-browser. At best, maybe a little peace of mind that at least some browsers won't let bookmarklets or third-party script modify the value.
Tested with Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9.
JavaScript ES6 (re-)introduced the
const
keyword which is supported in all major browsers.Apart from that,
const
behaves similar tolet
.It behaves as expected for primitive datatypes (Boolean, Null, Undefined, Number, String, Symbol):
Attention: Be aware of the pitfalls regarding objects:
If you really need an immutable and absolutely constant object: Just use
const ALL_CAPS
to make your intention clear. It is a good convention to follow for allconst
declarations anyway, so just rely on it.See Object.freeze. You can use
const
if you want to make theconstants
reference read-only as well.