To mutate means to change in form or nature. To understand mutation, think of X-Men. In X-Men, people can gain powers suddenly. You wonโt know when itโs going to happen. Imagine if a close friend next to you grows fur and turns blue all of a sudden. Wouldnโt it be scary?
In JavaScript, the same problem with mutations apply. If your code is mutable (can mutate), you might change (and break) something without knowing about it.
What is mutable, what is not?
Objects are mutable. Primitives are not.
You can change the properties of an object after it is created, but you cannot change the properties of a primitive.
// Objects can mutateconst egg = { name: 'Humpty Dumpty' }egg.isBroken = false
console.log(egg.name) // Humpty Dumptyconsole.log(egg.isBroken) // false// But primitives cannot mutateconst egg = 'Humpty Dumpty'egg.isBroken = false
console.log(egg) // Humpty Dumptyconsole.log(egg.isBroken) // undefinedWhy mutation can be scary
When you change an object, you can change the external state without you knowing. Look at the following code to see an example on how this might happen:
const egg = { name: 'Humpty Dumpty' }
function breakNewEgg(egg) { const newEgg = egg newEgg.isBroken = true}
breakNewEgg(egg)console.log(egg.isBroken) // trueIn breakNewEgg, we created a new variable, newEgg. Then, we mutate newEgg to include the isBroken property.
You can see that the original egg variable has changed even though we did not touch it. This is why mutation can be scaryโyou can change something without knowing.
Objects are passed as references
When you create an object, you create an โidentity cardโ for the object. When you assign the object to a variable, you link this variable to this identity card. This is called โpassing by referenceโ.
When you assign the object to another variable, you link the variable to the same identity card.
When you assign egg to a new variable, newEgg, newEgg points to the same object as egg. Since both variables point to the same identity card, itโs not a surprise that egg changes when newEgg changes.
Primitives are passed as values
When you declare a primitive, JavaScript does a similar thing. It creates a primitive and links the primitive to the variable.
But when you assign the same primitive to another variable, JavaScript creates another primitive and links the new primitive to the new variable.
As a result, we only care about what values primitive takes up. We donโt need to care about their references. This is why primitives are said to be โpassed by valuesโ (and also why we donโt have to worry about mutating primitives).
How to prevent mutation
Youโll learn how to prevent objects and arrays (since arrays are objects) from mutating in the next two lessons.
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson