In JavaScript, primitive values (numbers, strings, booleans, symbols, null, undefined) are copied by value, whereas objects (including arrays, functions, and plain objects) are referenced by memory address. Misunderstanding the boundary between shallow copies and deep copies is one of the most frequent causes of state mutation bugs.
1 const userA = { name : 'Alice' , score : 95 } ;
2 const userB = userA ; // COPIES REFERENCE ONLY!
3
4 userB . score = 100 ;
5 console . log ( userA . score ) ; // 100! userA was mutated!
2. Shallow Copy: Methods and Limitations A shallow copy creates a new outer object or array, but any nested objects or arrays inside it are still shared references.
Methods for Shallow Copying 1 Object Spread Operator: { ...source }
2 Array Spread Operator: [ ...sourceArray ]
3 Object.assign(): Object.assign({}, source)
4 Array.prototype.slice(): sourceArray.slice()
1 const original = {
2 title : 'Mastering JavaScript' ,
3 author : { name : 'Sarah' , country : 'Canada' } // Nested Object
4 } ;
5
6 // Shallow copy
7 const copy = { ... original } ;
8
9 copy . title = 'Advanced JavaScript' ; // Safe! Only copy.title changes.
10 copy . author . country = 'Germany' ; // DANGER! Mutates BOTH original and copy!
11
12 console . log ( original . author . country ) ; // 'Germany' (Shared reference!)
A deep copy recursively duplicates every level of nested objects and arrays, ensuring complete isolation in memory.
The Modern Standard: structuredClone() Introduced natively in modern JavaScript (Node.js 17+ and all modern browsers):
1 const order = {
2 id : 'ORD-9812' ,
3 items : [ { sku : 'KB-01' , qty : 2 } ] ,
4 createdAt : new Date ( )
5 } ;
6
7 // TRUE DEEP COPY:
8 const deepClonedOrder = structuredClone ( order ) ;
9
10 deepClonedOrder . items [ 0 ] . qty = 5 ;
11 console . log ( order . items [ 0 ] . qty ) ; // 2! Original is completely untouched!
12 console . log ( deepClonedOrder . createdAt instanceof Date ) ; // true! Preserves Date objects!
Features of structuredClone(): Handles nested objects and arrays to any depth. Supports cyclic references (objects referencing themselves). Preserves Date, RegExp, Map, Set, and ArrayBuffer instances. Limitation: Does not clone functions or DOM nodes (throws DataCloneError).4. The Legacy JSON Hack (and its gotchas) 1 const legacyCopy = JSON . parse ( JSON . stringify ( original ) ) ;
Critical Pitfalls of JSON.parse(JSON.stringify()): Discards functions and methods. Converts Date objects into ISO strings. Converts NaN and Infinity to null. Throws errors on circular references. Strips undefined values and Symbol keys. Technique Copy Depth Preserves Dates/RegExp? Handles Circular Refs? Clones Functions? Object.assign({}, obj)Shallow Yes (references) N/A Copies reference { ...obj }Shallow Yes (references) N/A Copies reference JSON.parse(JSON.stringify())Deep No (converts to string) Throws Error Drops functions structuredClone(obj)Deep Yes Yes Throws Error
Interactive Quiz • Knowledge Check
Practice Quiz What happens when you modify a nested object property inside a shallow copy created with {...original}?
A It throws a ReferenceError
B It mutates the nested property in both the copy and the original object
C It updates the copy only
D It automatically triggers structuredClone
What native modern JavaScript API provides true deep cloning out of the box?
A Object.deepClone()
B structuredClone()
C clone()
D Reflect.deepCopy()
What is a major limitation of using JSON.parse(JSON.stringify(obj)) to clone objects?
A It runs synchronously
B It loses Date types (converting them to strings), ignores undefined/functions, and crashes on circular references
C It cannot copy numbers
D It only works in Google Chrome
Which of the following creates a shallow copy of an array?
A const copy = array;
B const copy = [...array];
C const copy = array.push();
D const copy = Object.keys(array);
What error occurs if you pass an object containing a function to structuredClone()?
A TypeError: Function cannot be called
B DataCloneError
C SyntaxError
D Warning: undefined returned