🚀 A Subtle JavaScript Array Bug This looks harmless: const arr = [1, 2, 3]; const copy = arr; copy.push(4); console.log(arr); Output? [1, 2, 3, 4] Why did the original array change? Because arrays (like objects) are reference types in JavaScript. copy is not a new array. It points to the same memory location. This can create unexpected side effects in larger applications. ✅ Better approach: const arr = [1, 2, 3]; const copy = [...arr]; copy.push(4); console.log(arr); // [1, 2, 3] Now you’re working with a new reference. In JavaScript, copying data is not always copying values. Sometimes it’s copying references. Understanding this saves hours of debugging. What JS concept took you the longest to truly understand? #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering
Worth adding: spread only does a shallow copy. Nested objects still share the same reference. const arr = [{ id: 1 }]; const copy = [...arr]; copy[0].id = 99; console.log(arr[0].id); // 99 For deep cloning, structuredClone() is the clean modern option.
Important nuance: spread creates a new array structure, but not new object references inside it. For nested data, this can still cause subtle side effects.
Functional programing
First, this isn't a bug, all objects in JavaScript are passed by reference, this is standard in OOP languages. Whilst JavaScript doesn't have pointer types, or the ability to dereference them (because it's memory managed), it still follows the correct approach to object mutability for OOP. Second, spreading arrays is a shallow copy, I've seen more bugs from shallow copying where references to objects inside are retained than anything else. It results in a Frankenstein functional/OOP mess. StructuredClone will work, but only on objects that contain no functions. Reactive objects used by modern frameworks, Vue, Mobx etc, can't easily be cloned. Cloning objects is incredibly CPU intensive. The correct approach is to use the language as intended and create single sources of truth for objects and pass by reference. Only if you really need to clone something should you clone it. This dogma about copying objects comes from a bug in React state/render engine, even Dan Abramov acknowledges it was a mistake. “immutability by convention” (i.e., cloning objects to update state) was never a deliberate grand design — it was a pragmatic choice that later became a pain point, and the React Compiler exists largely to fix that legacy."