let sherlock = {
surname: 'Holmes',
address: { city: 'London' }
};
Step 2: Declaring the john Variable
let john = {
surname: 'Watson',
address: sherlock.address
};
Remember: a property always points at a value! It can’t point at another property or a variable. In general, all wires in our universe point at values.
By mutating an object used elsewhere in the program, we’ve made a mess.
Possible Solution: Mutating Another Object
One way to fix this would be to avoid mutating shared data:
// Replace Step 3 with this code:
john.surname = 'Lennon';
john.address = { city: 'Malibu' };
Alternative Solution: No Object Mutation
There is also another way we can make john.address.city give us "Malibu" while sherlock.address.city continues to say "London":
// Replace Step 3 with this code:
john = {
surname: 'Lennon',
address: { city: 'Malibu' }
};
You might notice there’s now an “abandoned” old version of the John object on our diagram. We don’t need to worry about it. JavaScript will eventually automatically remove it from memory if there are no wires pointing at it.
Pay close attention to which wire is on the left side of assignment.
Changing an object’s property is also called mutating that object.
If you mutate an object, your code will “see” that change via any wires pointing at that object. Sometimes, this may be what you want. However, mutating accidentally shared data may cause bugs.
Mutating the objects you’ve just created in code is safe. Broadly, how much you’ll use mutation depends on your app’s architecture. Even if you won’t use it a lot, it’s worth your time to understand how it works.
You can declare a variable with const instead of let. That allows you to enforce that this variable’s wire always points at the same value. But remember that const does not prevent object mutation!
08. Mutation
Let's go through the sherlock example:
Step 1: Declaring the sherlock Variable
Step 2: Declaring the john Variable
Remember: a property always points at a value! It can’t point at another property or a variable. In general, all wires in our universe point at values.
Step 3: Changing the Properties
Mutation
Mutation is a fancy way of saying “change”.
By mutating an object used elsewhere in the program, we’ve made a mess.
Possible Solution: Mutating Another Object
One way to fix this would be to avoid mutating shared data:
Alternative Solution: No Object Mutation
There is also another way we can make john.address.city give us "Malibu" while sherlock.address.city continues to say "London":
You might notice there’s now an “abandoned” old version of the John object on our diagram. We don’t need to worry about it. JavaScript will eventually automatically remove it from memory if there are no wires pointing at it.
Let vs Const
We can still mutate the object const points at:
Recap