Mutability and Immutability

Mutability and Immutability

What is it ? Why its important ? Explanation to even 5 year old will work

So here's very important and interesting topic . Mutable and Im-Mutable which we are gonna have read ahead. First we will go for im-mutable.

ImMutable

In stories princess can kiss the frog and it becomes the prince but if you kiss the frog in reality its not gonna be a prince it will remain a frog that's immutability . In coding terms strings and numbers are immutable that is once declared you can't change them.

Gifdescription

Let's go for an example

let me="Akshat"
let surname="Gupta"

me =me + surname // AkshatGupta

1) We created "me" now value of me is retrieved 2)surname is appended to the value of "me" 3)Now new memory space is allocated to the "me" variable 4) Previously created memory location is for now garbage collection .

Mutability

When princess kisses the frog it converted to the Prince that same frog is prince now. That is mutability for you . You can change the data types and data once declared with same memory location which was impossible with the strings and numbers.

Arrays and Objects are mutable types of data.

Let's take an example-

let obj={a:"akshat" b:"tanay"}
console.log(obj.a) // "akshat"
obj.a=4
console.log(obj.a) //4

disney.tumblr.com/post/42874855231/meet-cut.. Explanation- 1)A memory location is allocated to the object obj and its keys are stored in it. 2) Now when I print it , It returns what expected. 3)Now I m assigning the same a , a different value. 4)Now the value of a will be retrieved from the same memory location . 5)That mean's there is no need of the garbage collection since no new memory space is created.

Conclusion-

This is an amazing observation that how different data types works different that's helps us to work with them since objects and arrays are many times taken for granted .