views:

93

answers:

4

Hi

I am using visual studios 2010 and created a javascript file(jscript.js) and I saw on one page saying you can make constant variables in javascript like:

const x = 20;

bu to on another page I read it says you can't. So I am confused now what is it now?

Also in Visual studios when I write "const" it underlines it in the javascript file and goes syntax error.

+1  A: 

There's no const in ECMAScript (disregarding the dead 4.0 version, and ActionScript).

The const is available in JScript.NET, and some recent versions of JS engines e.g. Firefox, Opera 9, Safari as a vendor-specific extension.

KennyTM
Hmm I am not sure what Jscript.net is. Can it be used with jquery and stuff?
chobo2
@chobo2: JScript is Microsoft's version of Javascript (trademark issue, I think). JScript.NET is an extension of JScript for the .NET framework, like C# and VB.NET. I don't think you can use jQuery with it, as JScript.NET is never available on a browser.
KennyTM
[`const`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/const) is also available on the Mozilla implementations (Rhino, SpiderMonkey)
CMS
@CMS: Ah right. Updated.
KennyTM
@CMS Well I need my site to run on all browsers. So do other browser implement it too?
chobo2
A: 

No, there is no data type "const" in JavaScript.

JavaScript is a loosely typed language. Every kind of variable is declared with a var

Rajat
Looseness of typing is a bit orthogonal to constancy of binding, don't you think?
pilcrow
It is indeed. What I meant was that there is no special data types ( int,string, const) in JavaScript.
Rajat
+1  A: 

if you're looking for a read-only variable, you simulate that with something like

var constants = new (function() {
    var x = 20;
    this.getX = function() { return x; };
})();

and then use it like

constants.getX()
lincolnk
+2  A: 

const is a proposed feature of ECMAScript Harmony (together with a properly block-scoped let it is supposed to replace var and implicit globals). ECMAScript Harmony is a grab-bag of ideas for the next versions of ECMAScript.

const was also a part of ECMAScript 4.

ECMAScript 4 was never released and never will be, and ECMAScript Harmony will only be released in a couple of years. Therefore, you cannot reliably use it.

There are some implementations or derivatives of ECMAScript that implement const (ActionScript, for example). There are also some implementations that accept const as a synonym for var (IOW, you can use const, but it won't give you any protection.)

However, unless you absolutely can guarantee that your code will only run on very specific versions of very specific implementations of very specific derivatives of ECMAScript, it's probably better to avoid it. (Which is a real shame, because const and especially let are a huge improvement over var and implicit globals.)

Jörg W Mittag
Ya that won't do me any good. That sucks they really should have at least const in javascript.
chobo2