Immutability and Mutability in JavaScript Primitives
The five primitive data types in JavaScript are String, Number, Boolean, Undefined, BigInt, Symbol and Null, but Do you know?
If you are wondering how Javascript primitives are immutable by the design.
Here is the reason.
var country = "srilanka"
Do you think does it first created the country varible in the memory and assign the value hereafter?
No. It’s not how variables are assigned. Do not messed up with the hoisting. That’s another concept.
The variable flow is bellow.
- First of all value ( String, Number etc ) allocated it’s memory.
- Then the it will return the reference to the
country
variable name. - JS can’t find the memory location like C. So don’t messed up again.
- So if we print the
console.log(country)
to the browser or node console it will display the “srilanka” - So in the program we might have a chance to update the value of country. So we do
country = "india"
- So does it replace exiting “srilanka” value? No. It’s allocate a new memory slot. Please refer the diagrm.
- Thus returning the new reference of the new memory slot.
- That new reference is being allocated to the
country
variable. - Since JS engine does not keeps any reference to the “srilanka” string in the memory, it will be garbaged collected.
- This is same for all other Primitives as well.
So by the design Javascript primitives are immutable.
These are the reason why it’s immutable by the design.
- Predicable behaviour — We can predict that once we allocate the memory it does not changed.
- Simplicity — We can’t expect side effect since it’s does not mutate.
- Thread Safety — There will no race conditions
- Memory efficiency — JS engine can optimised the memory
- Functional Program — Couple of benefits to the functional programming including creation of pure function.
So Objects, Array mutable by default. Will bring new article for this topics. Thanks for reading. Happy coding!