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.

Frequently asked questions

How does JavaScript handle shallow copy?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Spread Operator" snippet in JavaScript uses `const merged = [...arr1, ...arr2];`.
Which code does the JavaScript example use?
The "Spread Operator" snippet uses `const merged = [...arr1, ...arr2];`, from the Variables & Constants section of the JavaScript cheat sheet.
Which stacks cover "shallow copy" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Spread Operator": Later properties overwrite earlier ones. Only performs a shallow copy -- nested objects are still shared by reference.