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.
This article is the first of a 3 parts series that explains how primitives and objects behave differently in the context of : mutability , copying(value vs reference) , being passed to functions.
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 π
MUTABILITY
always easier to understand with an example, let's create a string called me
and give it the value awesome
and an array of five numbers
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 0
note that me
didn't change at all while the first element in nums
became 0
as we wanted
Now for some reason I'll try to update the length
property of both me
and nums
and see if any changes happen.
Again, the string me
doesn't correspond to any change while nums
works as expected
why is that ?
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
MUTATING VS REASSIGNMENT
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.
CONCLUSION
- primitives are immutable
- objects are mutable
- mutability is not the same as reassignment
And that's it for this article, hope you find it helpful and stay tuned for the rest of this series
Top comments (0)