JavaScript Shallow Copy Conundrum: Why '...' Creates References

Part 1: Why JavaScript Why? 🚨 JavaScript Question (surprisingly tricky) What will be the result of this code? 🤔 const initialGameBoard = [ [null, null, null], [null, null, null], [null, null, null], ]; const copiedArray = [...initialGameBoard]; copiedArray[0][0] = 'X'; console.log(initialGameBoard[0][0]); ⬇️ ⬇️ ⬇️ Most people expect null. But the actual output is: 👉 'X' Why does this happen? [...] creates a shallow copy, not a deep one. That means: The outer array is copied The inner arrays are NOT copied Both arrays still reference the same nested arrays in memory So changing copiedArray[0][0] also changes initialGameBoard[0][0]. The correct way (for a 2D array) const copiedArray = initialGameBoard.map(row => [...row]); Now: The outer array is new Each inner array is also new No shared references ✅ Why doesn’t JavaScript do a deep copy automatically? Because predictability > magic. If JavaScript auto-deep-copied: How deep should it go? What about circular references? What about functions, Dates, Maps, Sets, DOM nodes? There’s no single “correct” answer. So JavaScript makes this rule very explicit: Copying is shallow by default. Always one level. This keeps behavior: predictable performant explicit (you control when deep copies happen) Key takeaway 🔑 Spread (...) copies values — and for objects/arrays, the value is a reference. If you want a deep copy, you must say so explicitly. Curious how many people got this right on the first try 👇 What would you have answered?

To view or add a comment, sign in

Explore content categories