Knowing how things behave is really important in programming as it gives a better understanding of the code you write and
it helps fixing bugs easily.
first things first let’s define primitives and objects:
primitives are strings , numbers , booleans , null ,
undefined , symbols , and bigInts.
objects are arrays and functions, and of course objects 😀
now let’s do some modifications, in
me I want the first character to be
A and in
nums I want the first number to be
me didn’t change at all while the first element in
0 as we wanted
Now for some reason I’ll try to update the
length property of both
nums and see if any changes happen.
Again, the string
me doesn’t correspond to any change while
nums works as expected
That’s because strings are immutable, meaning that we can only access the string’s characters and properties like
length but we can’t modify them at all.
On the other hand arrays are mutable, we can access and modify array elements and properties.
In fact, all primitives(strings, numbers , booleans , etc) are immutable while all objects are mutable.
You can modify object properties or array elements but you can’t modify a string’s character and you can’t modify a number.
If you want to make an object immutable you can use the built-in method
Object.freeze you can read about it here mdn reference
An interesting question is:
“How can’t we modify the string
me while we can say
me = "Awesome"; and that’ll update the string ? ”
well, the statement `me = “Awesome” is called reassignment and that’s not the same as mutating
let me explain the difference, think of a variable as a box containing a value, reassigning means throwing the Current value away and replacing it with another one.
while mutating means changing something about the value but without throwing it away.
- primitives are immutable
- objects are mutable
- mutability is not the same as reassignment