DEV Community

Discussion on: Declaring Variables in JavaScript

Collapse
daniel13rady profile image
Daniel Brady Author • Edited on

Someone asked me a really good question about const offline, so I recapped my answer in the comments:

Regarding this statement I made:

Sometimes, I want to give a name that never changes meaning, to a value that never changes. No single construct in JavaScript can enforce this.

Someone offline (to DEV, anyway) gave me a really good "But what about this..." example, so I wanted to share it and elaborate a bit on why what my statement still holds.

Basically, they wanted to know why this simple declaration doesn't provide complete immutability:

const x = 42;
Enter fullscreen mode Exit fullscreen mode

My answer is that, at least according to my own understanding of JavaScript, it does. However, it is not because of const alone. This declaration creates a box with contents that can be neither replaced nor modified because of two things:

  1. const prevents re-assignments
  2. numbers are immutable value types

If you replaced the initial value 42 with an object (arrays are a kind of JS object), then all of a sudden you've got a mutable value in an immutable variable, and the contents of your const box can be modified because the value itself can be modified:

/* Totally valid but very confusing so I don't like using `const` for this 🙂*/
const config = { some_setting: 42 }; // immutable variable
config.some_setting = "cat"; // mutable value
Enter fullscreen mode Exit fullscreen mode

This is what I meant when I said that no single construct in JavaScript can enforce complete immutability. Hope this helps!