ES6: Constants Can Change

I recently made the switch from the archaic JavaScript of yester-year that everyone loves to hate to ECMAScript 6 (otherwise known as ES6). If you’re like me, a person who hates change, then you may enjoy that one of the first things you will come to learn and love about ES6 is that it uses a new type of variable called “const.” Const, in a nutshell, allows you to declare immutable variables that can never be redefined within their scope.

I was stoked when I found out about this, man! I could actually officially declare constant variables. No longer did I need to declare variables and just not do anything with them, hoping I wouldn’t forget to not do anything with them. It was a miracle! Everything was working out beautifully. Then I discovered the truth…

…Const is not constant, nor truly immutable. My whole life was a lie!!!!

In most cases, const definitely seems constant.

PHP

1

2

3

constsillyString=“thisstring”;

constnumero=1;

constisImmutable=false;

I can not redefine numero to 9, for example, nor can I change isImmutable to “true.” Either case would bring me a bad time. This is as expected and could easily lead any programmer unfamiliar with the whole understanding of const to believe that the variable is truly immutable; but as it turns out, there are other ways than by definition that a variable can be changed. Const plays by a looser definition of immutability and allows for those other changes.

Take this example:

PHP

1

constparadigm={};

We have a new object, and it happens to be empty. You can’t redefine paradigm to be an object with a bunch of pre-defined properties, but you can give that object new properties.

paradigm.shifted = true; is a valid way to change what we once thought to be an immutable JavaScript variable. Even if you were to define paradigm with its ‘shifted’ property set to true within those brackets, you could still change the value of paradigm.shifted. A similar scenario can be made with const arrays. The array can be given new elements, as well as have elements removed and changed.

This can become a very tragic thing, when our understanding of constants shatters beneath our footing and turns out to be not so constant after all. However, there is a better way to explain and understand the confusing being-ness of const so that it is at least palatable. And no, it is not because it is JavaScript.

The reason these sorts of variables can be changed is because it is not the variable itself that is changing. The variable paradigm was defined as an object and remains as an object. It can never become some other thing. The same goes for the const array always being the thing that it is. The variables, in that sense, become their own sort-of scoped environment, and the items inside of that scope are the ones that can be added, removed, redefined, and otherwise changed. The const variable is then, in that sense, immutable. Our definition of immutable, however; might not be…