primitives vs objects in JAVASCRIPT : mutability

primitives vs objects in JAVASCRIPT : mutability:

 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 😀

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

result:

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.

results : 

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 methodObject.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 valuereassigning 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.

for example : 

CONCLUSION

  • primitives are immutable
  • objects are mutable
  • mutability is not the same as reassignment

from Tumblr https://generouspiratequeen.tumblr.com/post/644814855141015552

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s