What is Immutability
Immutability is a design pattern where something can't be modified after being instantiated. If we want to change the value of that thing, we must recreate it with the new value instead. Some JavaScript types are immutable and some are mutable, meaning their value can change without having to recreate it. Let's explain this difference with some examples:
As you can see in this case, although we changed the value of movie.episode
, the value of myEp
didn't change. That's because movie.episode
's type, number
, is immutable.
In this case however, changing the value of episode on one object also changed the value of the other. That's because movie1
and movie2
are of the Object type, and Objects are mutable.
Of the JavaScript built-in types, the following are immutable:
Boolean
Number
String
Symbol
Null
Undefined
And the following are mutable:
Object
Array
Function
String's an unusual case, since it can be iterated over using for...of and provides numeric indexers just like an array, but doing something like:
This will throw an error in strict mode and fail silently in non-strict mode.
Last updated