Deep copy

3 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Deep Cloning Arrays

JS · Arrays
Syntax
structuredClone(value)
Example
const original = [
  { name: "Ava", scores: [90, 85] },
  { name: "Leo", scores: [78, 92] },
];
const clone = structuredClone(original);
clone[0].scores.push(100);

console.log(original[0].scores); // [90, 85] (not affected)
console.log(clone[0].scores);    // [90, 85, 100]

Note structuredClone handles nested objects, arrays, Maps, Sets, Dates, RegExps, and more. Does NOT clone functions, DOM nodes, or prototypes.

structuredClone()

JS · Modern Features
Syntax
const clone = structuredClone(value);
Example
const original = {
  name: "Ava",
  scores: [95, 88, 72],
  metadata: { joined: new Date("2024-01-15") },
};
const clone = structuredClone(original);
clone.scores.push(100);
clone.metadata.joined.setFullYear(2025);

console.log(original.scores);          // [95, 88, 72]
console.log(original.metadata.joined); // 2024-01-15 (unchanged)

Note Built-in deep clone that handles Dates, Maps, Sets, RegExps, ArrayBuffers, circular references. Cannot clone functions, DOM nodes, or Error objects.

PYPython

Shallow vs Deep Copy

PY · Common Mistakes
Syntax
import copy
shallow = copy.copy(obj)
deep = copy.deepcopy(obj)
Example
import copy

original = [[1, 2], [3, 4]]
shallow = original.copy()
deep = copy.deepcopy(original)

original[0].append(99)
print(f"Original: {original}")
print(f"Shallow:  {shallow}")
print(f"Deep:     {deep}")
Output
Original: [[1, 2, 99], [3, 4]]
Shallow:  [[1, 2, 99], [3, 4]]
Deep:     [[1, 2], [3, 4]]

Note list.copy(), dict.copy(), and slicing (lst[:]) all produce shallow copies. Nested mutable objects are still shared. Use copy.deepcopy() when you need fully independent nested structures.

Frequently asked questions

How does JavaScript handle deep copy?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Deep Cloning Arrays" snippet in JavaScript uses `structuredClone(value)`.
Which code does the JavaScript example use?
The "Deep Cloning Arrays" snippet uses `structuredClone(value)`, from the Arrays section of the JavaScript cheat sheet.
Which stacks cover "deep copy" on this page?
JavaScript, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Deep Cloning Arrays": structuredClone handles nested objects, arrays, Maps, Sets, Dates, RegExps, and more. Does NOT clone functions, DOM nodes, or prototypes.