allenGKC / Just-Javascript-Reading-Notes

This is a reading notes of Just Javascript.
https://github.com/allenGKC/Just-Javascript-Reading-Notes
164 stars 56 forks source link

[Just JavaScript] 08. Mutation #8

Open allenGKC opened 4 years ago

allenGKC commented 4 years ago

08. Mutation

Let's go through the sherlock example:

Step 1: Declaring the sherlock Variable

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.

Step 3: Changing the Properties

john.surname = 'Lennon';
john.address.city = 'Malibu';

console.log(sherlock.surname); // "Holmes"
console.log(sherlock.address.city); // "Malibu"
console.log(john.surname); // "Lennon"
console.log(john.address.city); // "Malibu"

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:

// 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.

Let vs Const

const shrek = { species: 'ogre' };
shrek = fiona; // TypeError

We can still mutate the object const points at:

shrek.species = 'human';
console.log(shrek.species); // 'human'

Recap