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.