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.
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With