Mauro Bringolf

Currently geeking out as WordPress developer at WebKinder and student of computer science at ETH.

The 3 things you cannot do with a const variable in JavaScript

July 19, 2017
, ,

Babel 1 is a great open source project to invest energy into. One of the reasons is because it teaches you a lot about JavaScript and requires you to think about the language in a more strict and formal sense than other projects do. I enjoy this kind of thinking and have learned so many things from looking at Babel already. For a recent pull request 2 I had to consider all possible violations of the const keyword. This keyword was introduced in Ecmascript2015 aka ES6 and declares a new variable that is block scoped like a let declaration. What makes a const variable special is that it cannot be re-assigned after the initial declaration and definition. However, the value of a const variable is not immutable . Objects can be modified even when they were declared as constant. The reference is only guaranteed to be constant in the sense that it will always refer to the same thing even if this thing changes over time.

This might not be what you intuitively expect a constant to be, so this post might help you: It is a list of all things that will throw a runtime error with const variables but is fine with let and var variables. This is the complete list of violations I have found so far (and that currently exist in Babel tests).

1. Explicit reassignment

This is the most obvious one. A const reference cannot be reassigned to point to a different thing. This includes all various forms of assignment including destructuring.

const a = { x : 3 };
a = 7;
({a} = {a: 3})
a /= 3;
a **= 17;

2. Shorthand increment and decrement

But explicit assignments like above are not the only assignments in JavaScript. The next one is still quite obvious:

const a = 19;

3. for-in and for-of loop

This one surprised me, especially because it is not always a violation and might only be decidedable at runtime.

const a = 'whatever';

// Tries to reassign a to elements
for(a of [1,2,3]) {}
for(a in { x: 1 }) {}

// This is fine
for(a of []) {}
for(a in {}) {}

Please let me know if you encounter or can think of others so we can obey Cunningham’s law!3.