Is it possible to simulate constants in Javascript using closures? If so, can you please furnish me with an example?
-
1Why not just, you know, declare a regular variable? Why muck about with something overly complicated? – kquinn Mar 08 '09 at 02:27
-
Homework?..hardly! And why 'muck about'? because i want to use constants NOT variables. They are total different types used for totally different purposes. – Gary Willoughby Mar 08 '09 at 02:33
-
The same way any program would differ using constants instead of variables. It would make sure nobody using my framework could assign values to the constants used. I can't believe i'm having to educate people on what constants are used for in the comments section!!! – Gary Willoughby Mar 08 '09 at 02:39
-
Javascript is a dynamically typed language; for good or for ill, modern dynamic languages often do not have built-in constant support. It's simply not ingrained in the dynamic language ethos like it is the older static languages. – kquinn Mar 08 '09 at 02:43
-
Thus the question to simulate them. – Gary Willoughby Mar 08 '09 at 02:45
-
My point is, constants and dynamic languages are, on some level, *opposed to each other*. If you want to force something into the language that it doesn't support natively, you need to think about why you're doing it and, importantly, why it was left out in the first place. – kquinn Mar 08 '09 at 02:47
-
So why is there a const keyword in the javascript spec? – Gary Willoughby Mar 08 '09 at 02:51
-
1It's *not* in the language spec. It's in *one vendor's extension* (and since copied, probably for compatibility as much as anything else). Just because a language has a feature, does not mean you should use it! – kquinn Mar 08 '09 at 02:52
-
Plus constants and dynamic types are not mutually exclusive. You can still have a dynamically typed constant. – Gary Willoughby Mar 08 '09 at 02:52
-
@kquinn: technically, JavaScript is the Mozilla implementation of ECMAScript. So the const keyword is in the JavaScript spec. – Shog9 Mar 08 '09 at 02:53
-
@kquinn: Why shouldn't i exploit a feature of the language? Is this some ego trip with you now? I don't agree with anything you have said and i think you are very wrong to use variables when indeed i want a constant. – Gary Willoughby Mar 08 '09 at 02:54
-
@Ctrl Alt D-1337: no. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf – Miles Mar 08 '09 at 02:54
-
Is the ReadOnly attribute any use? – Tim Matthews Mar 08 '09 at 02:58
-
1I'll freely admit to ignorance (read 'bliss') as regards the JS/ECMAS mess. But I think my point stands. The 'const' keyword is easy enough to use. But these insane class-hacks simply are not worth the trouble, especially since in a dynamic language they're all bypassable anyway. – kquinn Mar 08 '09 at 02:59
-
@Ctrl Alt D-1337: no, property attributes are part of the implementation and are not exposed through the language. – Miles Mar 08 '09 at 03:03
-
A straight ECMAScript 3 implementation is, at this point, quite archaic. If you need to support such an implementation, then obviously using features introduced after that spec was standardized is a Bad Idea. If you don't, then use what makes sense. Or, if you like pain, try to follow ECMAScript 4. – Shog9 Mar 08 '09 at 03:07
-
I mean, you can write K&R-style C functions too, if you absolutely need to support every C compiler ever. – Shog9 Mar 08 '09 at 03:09
-
As for being able to bypass hacks... C++ has const_cast, but that doesn't make const variables any less useful. If you're determined to override something, nothing wrong with being able to... Just make it hard enough that you don't do it by accident. – Shog9 Mar 08 '09 at 03:10
-
*sigh*... All this, and it's probably a dupe anyway... http://stackoverflow.com/questions/130396/are-there-constants-in-javascript – Shog9 Mar 08 '09 at 03:17
-
@Shog9: I don't consider ES3 archaic at all, in terms of real-world web development; there is no more recent widely-supported dialect, *even* if you ignore IE and only look at browsers like FF, Safari, and Opera. – Miles Mar 08 '09 at 03:26
-
1If you're talking real-world web development, then you can't ignore IE. If you're using a specific JS engine (scripting your desktop app, writing Greasemonkey scripts, server-side, whatever), then it really only matters what that engine supports. – Shog9 Mar 08 '09 at 04:02
-
Is JScript going to implemnt const like in Javascript anytime soon? – Tim Matthews Mar 08 '09 at 04:22
4 Answers
Firefox and Chrome both support the const
keyword. IE does not. So if you need constants and don't need to support IE, const
isn't a bad choice. Keep in mind though, neither browser produces a runtime error when a value is assigned to a const
; the values merely remains unchanged.
Otherwise, you must use functions to define constants that cannot be modified:
function PI() { return 3.14159; }
var area = radius*radius * PI();
Of course, you could just write code that never modifies certain variables, and maybe establish a naming scheme for such variables such that you recognize that they will never need to be modified...
// note to self: never assign values to variables utilizing all-uppercase name
var PI = 3.14159;
Another option for "simulating" constants would be to use the property definition functionality available in some browsers to define read-only properties on an object. Of course, since the browsers supporting property definitions don't include IE, that doesn't really help... (note that IE8 does support property definitions after a fashion... but not on JavaScript objects)
Finally, in very contrived scenarios you might use function arguments as constants (perhaps this is what you were thinking of when you suggested closures?). While they behave as variables, they remain scoped to the function in which they are defined and cannot therefore affect the values held by variables with the same name outside of the function in which they are modified:
var blah = 3;
var naw = "nope";
(function(blah, naw)
{
blah = 2;
naw = "yeah";
alert(naw + blah); // "yeah2"
})(blah, naw);
alert(naw + blah); // "nope3"
Note that something similar to this is commonly used by jQuery plugins, but for the opposite reason: jQuery code is usually written using the $
shorthand to refer to the jQuery object, but the library is intended to continue working even if some other code redefines that symbol; by wrapping library and plugin code in anonymous functions with a $
parameter and then passing in jQuery
as an argument, the code is isolated from changes other libraries might make to the value of $
later on.
See also: Are there constants in Javascript?
-
1Of course, for your first example, you could just set PI to be a *different* function—there's no real enforced const-ness there. – Miles Mar 08 '09 at 02:50
-
Yes; JavaScript tends to make overriding code extremely easy if that is your intention. However, if your intention is to prevent unintentional assignment of a new value to a constant, the function method would serve. – Shog9 Mar 08 '09 at 02:52
-
-1: Same reason as Miles gives. Also why pass in blah and naw when you don't even use their values. Just define new local variables. – Thomas Eding Jan 11 '10 at 23:16
-
Um, same reply I gave to Miles then. Also... did you miss the "very contrived scenario" bit? That last technique is *only* useful when you want a name to remain under your control for a given bit of code *regardless* of what other code does elsewhere... For example, a jQuery plugin that wants to refer to jQuery using `$` even if some other library redefines that symbol to mean something else. If you don't have to worry about code you don't control, then it makes no sense. – Shog9 Jan 12 '10 at 00:40
You can create read-only, named constants with the const keyword (Implemented in JavaScript 1.5).

- 807,428
- 183
- 922
- 838
-
1A quick Google shows this is *not* supported in all browsers... particularly, (yep, you guessed it), IE7 or IE8b2. – kquinn Mar 08 '09 at 02:41
-
-
Who cares that IE doens't support this. People develop their JS in FireFox. So they will notice there that stuff doesn't work as expected and then fix it before releasing it. So there will never be a problem in IE. – Pim Jager Mar 08 '09 at 09:21
-
Firefox supports this, but IE - doesn't. So writing such code isn't a good practice. – unorsk Mar 08 '09 at 09:48
To declare :
function globals(){
const x1="something";
const x2="otherthing";
return{
getX1=function(){
return x1;
},
getX2=function(){
return x2;
}
}
}
var globalConstants=globals();
To access :
globalConstants.getX1();

- 81
- 5
This is as far as i got:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function Scope()
{
return function()
{
return {Constant: 1}; //Object literal
};
}
var Scope = Scope();
</script>
</head>
<body>
<script type="text/javascript">
document.write(Scope().Constant + "<br />");
//The following line of code has no effect and fails silently.
Scope().Constant = 6;
document.write(Scope().Constant + "<br />");
</script>
</body>
</html>
This approach allows me to extend the scope to have more than one constant member variable by extending the object literal.

- 50,926
- 41
- 133
- 199
-
-
-
thanks, i'm learning more. You think you know javascript then along comes a feature that becomes popular and you think i must revisit this language and realise you know nothing. lol. – Gary Willoughby Mar 09 '09 at 12:16