Immutability
var obj; | |
var anotherObj; | |
// A mutable example. | |
obj = { | |
'field': 'value' | |
}; | |
// An example of unintended mutability. By default, JavaScript assigns a *reference* to anotherObj, pointing | |
// at the *same* object. Therefore, when we go to modify anotherObj, we accidentally modify obj too. | |
anotherObj = obj; | |
anotherObj.field = 'another value'; | |
// Prints 'another value'. | |
console.log(obj.field); | |
// Prints 'another value'. | |
console.log(anotherObj.field); | |
// Prints true | |
console.log(obj === anotherObj); | |
// Can we do this immutably? | |
obj = { | |
field: 'value' | |
}; | |
anotherObj = {...obj}; | |
anotherObj.field = 'another value'; | |
// Prints 'value'. | |
console.log(obj.field); | |
// Prints 'another value'. | |
console.log(anotherObj.field); | |
// Prints false. | |
console.log(obj === anotherObj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment