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?
For a while, I specified "constants" (which still weren't actually constants) in object literals passed through to
with()
statements. I thought it was so clever. Here's an example:In the past, I also have created a
CONST
namespace where I would put all of my constants. Again, with the overhead. Sheesh.Now, I just do
var MY_CONST = 'whatever';
to KISS.Rhino.js
implementsconst
in addition to what was mentioned above.My opinion (works only with objects).
Try! But understand - this is object, but not simple variable.
Try also just:
Mozillas MDN Web Docs contain good examples and explanations about
const
. Excerpt:But it is sad that IE9/10 still does not support
const
. And the reason it's absurd:They don't implement it because other browsers didn't implement it correctly?! Too afraid of making it better? Standards definitions or not, a constant is a constant: set once, never changed.
And to all the ideas: Every function can be overwritten (XSS etc.). So there is no difference in
var
orfunction(){return}
.const
is the only real constant.Update: IE11 supports
const
:IE does support constants, sort of, e.g.:
I too have had a problem with this. And after quite a while searching for the answer and looking at all the responses by everybody, I think I've come up with a viable solution to this.
It seems that most of the answers that I've come across is using functions to hold the constants. As many of the users of the MANY forums post about, the functions can be easily over written by users on the client side. I was intrigued by Keith Evetts' answer that the constants object can not be accessed by the outside, but only from the functions on the inside.
So I came up with this solution:
Put everything inside an anonymous function so that way, the variables, objects, etc. cannot be changed by the client side. Also hide the 'real' functions by having other functions call the 'real' functions from the inside. I also thought of using functions to check if a function has been changed by a user on the client side. If the functions have been changed, change them back using variables that are 'protected' on the inside and cannot be changed.
It also seems that security is really a problem and there is not way to 'hide' you programming from the client side. A good idea for me is to compress your code so that it is really hard for anyone, including you, the programmer, to read and understand it. There is a site you can go to: http://javascriptcompressor.com/. (This is not my site, don't worry I'm not advertising.) This is a site that will let you compress and obfuscate Javascript code for free.