ES2015 Const Declarations in Babel

Babel 6

This is probably the version of Babel you are using by the time I'm writing this note.

Take the following piece of code:

JavaScript
        
const a = true
a = false
        
      

You can try to compile it through Babel 6, here is the result:

Shell
        
repl: "a" is read-only
  1 | const a = true
> 2 | a = false
    | ^
        
      

It doesn't compile. The result is understandable, we tried to change the value of a and you can't re-assign a constant.

Babel 7

I used the same piece of code, we will see the result if you compile it through Babel 7.

We don't get the compile error anymore, but here is the generated code:

JavaScript
        
// Runtime helpers

function _readOnlyError(name) {
    throw new Error("\"" + name + "\" is read-only");
}

// Code

var a = true;
a = (_readOnlyError("a"), false);
        
      

And as you would expect here is the result when you actually run this code in your browser:

JavaScript
        
Uncaught Error: "a" is read-only
  at _readOnlyError (:4:11)
  at :10:6
        
      

Why did we change it?

Basically the error at compile-time in Babel 6 is now a runtime error in Babel 7.

Take the following code:

JavaScript
        
const a = true

if (false) {
  a = false
}
        
      

This code is perfectly fine and according to the specification, it should run without any errors, because we won't ever reach the constant re-assigning.
Babel 6 wasn't spec compliant in that regard because it will refuse to compile the code and throw an error.

Babel 7 will generate the following code:

JavaScript
        
// Code

var a = true;

if (false) {
    a = (_readOnlyError("a"), false);
}
        
      

You can avoid the runtime error

Of course you shouldn't ever re-assign a constant, but it can happen by mistake.
You can use a linter because most of them will warn you about that.

Credits

This work has been done by maurobringolf, you can see his PR here: babel/babel#5930.

Contact me

Sven Sauleau

Say hello: sven.sauleau@xtuc.fr.

Ping me on Twitter: @svensauleau.

© XTUC SAS
N° SIRET : 821 797 891 00016, RCS Strasbourg TI 821 797 891