Shallow copy

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Spread Operator

JS · Variables & Constants
syntax
const merged = [...arr1, ...arr2];
const merged = { ...obj1, ...obj2 };
example
const defaults = { theme: "light", lang: "en" };
const prefs = { theme: "dark", fontSize: 16 };
const config = { ...defaults, ...prefs };
console.log(config);
output
{ theme: "dark", lang: "en", fontSize: 16 }

Note Later properties overwrite earlier ones. Only performs a shallow copy -- nested objects are still shared by reference.

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.