DEV Community

Discussion on: "Variables declared with const cannot change" ... well kinda...

Collapse
 
sleeplessbyte profile image
Derk-Jan Karrenbeld

Hi there Austin,

I saw on Twitter that you may think that this behaviour is special for Arrays or Objects (as in, it's a quirk) and I think that might be caused by the common confusion of what const actually means. Let me write out what I mean:

  • Primitives in JavaScript are always immutable, regardless of the const, var or let declaration.
  • Non-primitives are always mutable when they're created. It's possible to define properties that are not configurable (changable / deletable) or writable, and it's possible to force all properties to be non-configurable and non-writable, (including the __proto__ property) and prevent new properties from being defined via Object.freeze. You can use Object.seal if you to disallow removing/adding new properties, but still allow writing to those properties.

Okay great. So what?

const only says something about the variable binding. It only means that you won't be able to re-assign something to the binding, and says nothing about the value that's bound. This behaviour is the same between primitives and non-primitives:

const hello = 32
hello = 42
// => TypeError: Assignment to constant variable.

const goodbye = [32]
goodbye = [42]
// => TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

You can indeed change the goodbye value by not re-assigning it:

goodbye[0] = 42
Enter fullscreen mode Exit fullscreen mode

but that behaviour has nothing to do with const (or let, or var).

You won't be able to demonstrate the same with say... a number, because numbers are primitives, and can never be changed. There are no methods on numbers to mutate them, just like there are no methods on the other primitives, so it's hard to show equivalence.

I hope this makes sense, but please feel free to ask more if you want to know more!