Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use constant variables in JavaScript? [duplicate]

I read on one site that you can make constant variables in JavaScript like:

const x = 20; 

but on another site I read that you can't. So I am confused now what is it now?

Also in Visual Studio 2010 when I write const it underlines it in the JavaScript file and shows syntax error.

like image 953
chobo2 Avatar asked May 12 '10 18:05

chobo2


People also ask

Can we use const in for loop JavaScript?

for/in and for/of expose the same behavior for const and let , but the normal for loop does not. It explicitly treats const differently (understandably maybe). You simply say that it is "declared once" but that simplifies it too much IMO.

Can constant variables be reassigned?

The value of a constant can't be changed through reassignment, and it can't be redeclared. The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned.

Can a const variable be modified JavaScript?

Yes, properties and methods be changed for a const object. A const declaration does not mean that the value of the variable cannot be changed. It just means that the variable identifier cannot be reassigned.

Are constants variables in JavaScript?

JavaScript Constants Once a constant is initialized, we cannot change its value. Simply, a constant is a type of variable whose value cannot be changed.


1 Answers

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.)

like image 160
Jörg W Mittag Avatar answered Oct 06 '22 00:10

Jörg W Mittag