Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 why can I reassign a constant when defined in a loop

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?

enter image description here


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.

like image 899
Simon Staton Avatar asked Feb 05 '15 12:02

Simon Staton


1 Answers

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

  1. Else if the binding for N in envRec is a mutable binding, change its bound value to V.
  2. 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.

like image 82
georg Avatar answered Oct 24 '22 17:10

georg