Is spread a deep copy?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn Is spread a deep copy?
Definition:
Spread syntax creates a new outer object or array by copying its enumerable contents. It is a shallow copy, so nested objects are still shared references. This matters when updating React state or copying request data that another part of the application may modify.
Key points:
-
No.
{ ...user }copies only the first level. -
Nested objects still share references.
-
Copy each changed level, or use
structuredClonefor supported data types. -
Changing a top-level field in the copy does not change that field in the original.
-
structuredClonesupports many nested data types, but not functions and not every custom object behavior.
Example:
const original = { address: { city: 'Surat' } };
const copy = { ...original };
copy.address.city = 'Ahmedabad';
console.log(original.address.city); // Ahmedabad- Both outer objects still point to the same nested
addressobject.
Interview point:
- Show the nested reference that remains shared; do not describe spread as complete immutability.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “Is spread a deep copy?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.