JavaScript Shallow Copy Myth Busted

💡 Most devs think shallow copies always affect the original… but that’s not true! Let’s clear this common JavaScript misconception 👇 🧩 Example 1 — Primitives let obj = { a: 1, b: 2, c: 3 }; let obj2 = { ...obj }; obj2.b++; console.log(obj.b); // 2 ✅ unchanged ➡️ Here b is a primitive (number). Primitives are copied by value, so obj and obj2 have separate copies. Incrementing obj2.b doesn’t affect obj.b. ⚠️ Example 2 — Nested Objects let obj = { a: 1, b: { x: 10 } }; let obj2 = { ...obj }; obj2.b.x = 99; console.log(obj.b.x); // 99 ❗changed ➡️ Here b is an object, and a shallow copy only copies its reference. Both obj.b and obj2.b point to the same memory. So changing one affects the other. 💬 TL;DR Shallow copy doesn’t always affect the original — it depends on what’s inside the object. Primitives → safe Objects → shared #JavaScript #Frontend #WebDevelopment #ReactJS #CodingTips #Programming #JSFacts

To view or add a comment, sign in

Explore content categories