Understanding Javascript immutable variable

Values are immutable; variables are not; they hold a reference to their (primitive) values.

The three primitive types string, number and boolean have corresponding types whose instances are objects: String, Number, Boolean.
They are sometimes called wrapper types.

The following values are primitive:

  • Strings: “hello”
  • Numbers: 6, 3.14 (all numbers in JavaScript are floating point)
  • Booleans: true, false
  • null: usually explicitly assigned
  • undefined: usually the default (automatically assigned) value

All other values are objects, including wrappers for primitives.

So:

  • Objects are mutable by default
  • Objects have unique identities and are compared by reference
  • Variables hold references to objects
  • Primitives are immutable
  • Primitives are compared by value, they don’t have individual identities

You might find The Secret Life of JavaScript Primitives a good explanation.

Also, in ES6 there is a new const keyword, that creates a read-only named constant that cannot change value through assignment or be re-declared while the script is running.

Hope this helps!

Leave a Comment