In JavaScript only objects and arrays data types are mutable and other data types like Number
, String
are immutable.
Mutable is something that can be updated/changed, and immutable is something that can not be changed once created. But what exactly it means to be update or changed?
Let's look at this code snippet and see how immutable data gets updated in JavaScript.
let a = 100
a = a + 100
In above example, we declared a variable a
and assigned a numeric value 100 to it.
As we know Number
data type is immutable, it means once we created variable a
in line 1 we can not changed its value. But we are changing/updating a
value from 100 to 200. Let's see step by step what's happening -
- We declared variable
a
and assigned it a numerice value 100. - In line 2, a value 100 is being added to exisiting value of
a
. - The resultant value 200, which is immutable is stored at difference memory address than 100 was stored.
- Now, updated variable
a
is pointing to newly created memory address. - Previous memory address (which we created in line 1 of code snippet) will be garbage collected.
This events happens everytime you change a immutable data (numbers, string etc) in JavaScript.
Let's see how mutable data gets updated -
const hero = { name: "Batman" }
const newHero = hero
newHero.name = "Aquaman"
newHero.name === hero.name
In line 1 we declared a variable hero
and assiged a object data. In line 2 we are declaring a new variable named newHero
and setting its value to equal to hero
.
While assigning a value to newHero
object, JavaScript sees that hero
variable is a mutable object, so instead of allocating a new momory to newHero
variable it just points newHero
to same memory address as hero
object is pointing to.
Now both objects hero
and newHero
are sharing the exact same physical memory. so any changes made to newHero
objects will also reflect into hero
object and vice-versa.
Conclusion
In short, mutable data is mutable because you can update the data by not changing its location in physical memory, for eg. if you update object property, the changes are being made to existing memory, memory address remains same.
But for immutable data, every change made to it will cause a new memory allocation and previous memory will be garbage collected. That's why two immutable variable will never share same memory location.