Just-Javascript-Reading-Notes icon indicating copy to clipboard operation
Just-Javascript-Reading-Notes copied to clipboard

[Just JavaScript] 08. Mutation

Open allenGKC opened this issue 4 years ago • 0 comments

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

  • Objects are never “nested” in our universe.
  • 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!

allenGKC avatar Jul 09 '20 09:07 allenGKC