Created
December 27, 2019 04:02
-
-
Save bhaveshdaswani93/8e7d016388513d0ac5cd7266dc3b1724 to your computer and use it in GitHub Desktop.
In this example i will try to explain immutability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let mutateObj = { | |
first_name:'lorem', | |
last_name:'ipsum' | |
}; | |
let immutateObj = { | |
first_name:'irum', | |
last_name:'egestas' | |
}; | |
const mutatingState = (obj) => { | |
obj.first_name = 'ullamcorper'; | |
return obj; | |
} | |
const immutatingState = (obj) => { | |
const copiedObj = Object.assign({},obj); | |
copiedObj.first_name = 'facilisis'; | |
return copiedObj; | |
} | |
mutatingState(mutateObj); | |
console.log(mutateObj); | |
/* | |
above output { | |
first_name:'ullamcorper', | |
last_name:'ipsum' | |
}; | |
in the above function we have mutated the orignal state | |
*/ | |
const newObj = immutatingState(immutateObj); | |
console.log(immutateObj); | |
/* | |
newObj will be | |
{ | |
first_name:'facilisis', | |
last_name:'egestas' | |
}; | |
and immutateObj will not be changed and it value is | |
{ | |
first_name:'irum', | |
last_name:'egestas' | |
}; | |
here the orignal state is not change | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment