You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
🧠 JavaScript Copy vs Reference
A small note I wrote while learning how objects behave in JavaScript.
Sometimes when we assign variables we think we made a copy,
but actually we only created a reference.
Understanding this saved me from many bugs.
1️⃣ Primitive Values (Safe Copy)
Primitive values are copied automatically.
Examples:
Here
ais not affected because primitives are copied.2️⃣ Objects (Reference)
Objects behave differently.
Why?
Because
bdoes not copy the object.It only stores a reference to the same object in memory.
Both variables point to the same object.
3️⃣ Creating a Safe Copy
We can use the spread operator.
Now
aandbare different objects.4️⃣ Common Mistake
This does NOT copy the object.
This creates a new object that contains
a.If you modify it:
Then
awill change too.5️⃣ Important Note
The spread operator makes a shallow copy, not a deep copy.
Example:
Now:
Because the nested object is still a reference.
🎯 Rule I Remember
Understanding this helps avoid many bugs when working with:
✨ Small concepts like this make big differences in real projects.
All reactions