I am playing around with some pointless logic to better understand ES6 and have noticed a strange occurrence when defining a constant.
It seems possible to change a constant assignment when defined in a loop:
"use strict";
for(const i=0;i<10;i++){ //seting constant in loop
console.log(i); //is reassigned and incremented 0,1,2,3...
}
const e = 0; //setting constant outside loop
for(;e<10;e++){ //cannot reassign constant
console.log(e);
}
Is this expected behavior and can anyone shed some light on why this occurs, is declaration in the loop different?
Update from Statements/const
This declaration creates a constant that can be global or local to the function in which it is declared. Constants are block-scoped.
When you modify an "immutable binding", the current draft only throws in the strict mode:
As @kangax pointed out, reassignment of a constant should always throw, since const
creates an "immutable binding" with the strict
flag on (here):
If IsConstantDeclaration of d is true, then
Call env’s CreateImmutableBinding concrete method passing dn and true as the arguments.
and then:
SetMutableBinding (N,V,S) ...
- Else if the binding for N in envRec is a mutable binding, change its bound value to V.
- Else this must be an attempt to change the value of an immutable binding so if S is true throw a TypeError exception.
However, node only throws in strict mode:
"use strict";
const e = 0;
e = 42; // SyntaxError: Assignment to constant variable.
(it's not clear why this is a "SyntaxError")...
In the non-strict mode, the assignment to the constant is silently ignored:
const e = 0;
e = 42;
console.log(e); // 0
Tested with node v0.10.35 with --harmony
flag.
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