The question in that poll may seem simple but in reality, there is a few things going on.
If you are wondering the answer to that question is steak
.
Let’s break that down.
Pass By Reference
Objects within Javascript are pass by reference by default.
What that means is variable definition and assignment are linked to the object as a reference.
So, any changes to that object means... You are changing the original object ❗️
The reason this is not ideal is because you are mutating the value of an object for all the code using that object.
And that can lead to really hard to debug bugs.
So, what can you do about it ?
Well, that’s where cloning comes in.
Let‘s see how that works.
Object Cloning
One way to combat against this issue is through cloning of the object when re-assigning or when you are changing it.
When you clone an object, you are essentially creating a new copy of it.
So, that variable no longer references the original, it now references the new copy.
This way when you make changes to that object, it doesn’t affect the original object.
So, how do you do this in Javascript ?
Let’s look at some techniques you can use to achieve this.
Object Cloning techniques (Javascript)
Here are 3 methods for cloning objects:
Object.assign - creates a shallow copy of the object
Spread operator - creates a shallow copy of the object
structuredClone - creates a deep copy of the object
The difference between shallow and deep is that deep will copy all the nested objects within the object. Shallow will not do this.
And there you have it!
Remember be careful when mutating or changing references to objects.
It can leads to nasty bugs!
If you learned something new or enjoyed this article, be sure to give it a like or share with someone you know!