Skip to content

Instantly share code, notes, and snippets.

@sean-roberts
Last active May 26, 2020 19:09
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sean-roberts/5710852 to your computer and use it in GitHub Desktop.
Save sean-roberts/5710852 to your computer and use it in GitHub Desktop.
Immutable vs Mutable in JS - the immutable (unable to change or mutate) values are primitive values - numbers, strings, booleans, null, undefined). While the mutable are all other objects. They are generally referred to as reference types because the object values are references to the location, in memory, that the value resides.
// start with at string
var s = "my string";
//change its value (remember this changing of value is by value not reference)
s.toUpperCase();
// assign it to t
var t = s;
//t is now "my string"
//this is because, when we changed the value of s to be uppercase, we were actually only referring to s's value not the
// location in which it is stored. Therefore the next time it is fetched, it is the same as the originally stored value
//objects on the other hand are reference types so when we mutate them, we are mutating the value that is stored in memory
//so the next time it is use, it will pull the value from memory with the mutations included
//create and mutate
var obj = { z : 1 };
obj.y = 2;
obj.x = 3;
// obj, in memory, now stores all three properties
// a weird thing to come across is that because this is by reference, when you assign it to a new object like:
var otherObj = obj;
//otherObj is now pointing at the same location that obj is
//so changing any properties in otherObj will change them in obj, and vice versa
otherObj.a = 4;
//obj will also have a property named a with the value of 4
//if you don't want this you must create a new object and explicitly copy over the properties
var finalObj = {};
//- foreach property in obj
for(prop in obj){
//add it to the new object
finalObj[prop] = obj[prop];
}
@alhridoy
Copy link

Thanks!

@ashutoshjha1409
Copy link

Instead of iterating over the properties and explicitly copying them to a new object. One can make use of Object.assign()
For e.g
var finalObj = Object.assign({}, obj);

Here is the documentation link

@pritambhanji
Copy link

But we can do like
var myString = "Pritam";
myString = "Deepti";
we can change the value of string then how it is immutable?

@azmanahmed21
Copy link

@juliecoding
Copy link

juliecoding commented Apr 1, 2018

In short @pritambhanji, you're NOT changing the value of the string, you're changing the assignment of the variable. myString can change to any number of things, but "Pritam" still equals "Pritam".

@sislinigeria
Copy link

great

@Zill-Saqee
Copy link

good i learned very easily

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment