2.) That's nice but JS semantics do not actually hold up. The intent is for a constant, the reality is there is a small window where the wrong results can be observed. Engines don't actually do any more optimizations than for var or let; in fact, your code may actually be slower due to the live-range hole checks.
function f() { console.log(a); const a = 1; console.log(a); }
...actually returns this:
undefined 1
So you get partially compile-time semantics (you can't assign to a) but partially run-time semantics (a only gets its value when initialised). Simply propagating the value of a's initialiser to all places where the variable is used is wrong, as this behaviour's required by the spec.
> ReferenceError: can't access lexical declaration `a' before initialization
> The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated.
I.e. given a variable declared with `const`, you may not access it before it is set.
[1] http://people.mozilla.org/~jorendorff/es6-draft.html#sec-let...
The trouble with this approach is that runtime checks are only a guarantee that the code you've _exercised_ does not break the contract.
In that respect, `const` is deeply different than `.freeze`, in the same way that runtime assertions are deeply different than type checking.
I am simply repeating the well-known benefits to immutables which is completely orthogonal to a type system, static or otherwise.
const a = {};
Object.setPrototypeOf(a, SomethingElse);Remember I have said const PLUS Object.freeze() Both are needed to get the true immutable effect.
Javascript is dynamically weakly typed but it is still typed, typeof/instanceof exist for a reason.
my point is if you are using a weakly typed language, it doesn't care much about developer intent with respect to type. so why would it be concerned with developer intent with respect to mutability? seems arbitrary.
1) It means that every place the const appears it can be replaced with the const's value. Type checking can be streamlined, less indirection.
2) It communicates the developer's INTENT in an enforced manner. No later code change can accidentally make the const suddenly non-const.
3) const + deep Object.freeze() makes for a complete const.
Sure a human could hypothetically scan the code to see that the value has not been reassigned. This falls apart in practice. As soon as the company has a few dozen developers the code is constantly changing and such manual analysis would have to be constantly done.