Deep Clone in JavaScript

Level 4261 keystrokes

JSON.parse(JSON.stringify()) creates a deep clone, copying nested objects independently.

JavaScript code

// Deep clone function using JSON serialization
// Note: doesn't work with functions, undefined, or circular references
1const deepClone = obj => JSON.parse(JSON.stringify(obj));
// Create an object with nested structures
2const original = { a: 1, b: { c: 2, d: [3, 4] } };
// Create a deep clone
3const cloned = deepClone(original);
// Modify the cloned object
4cloned.b.c = 999;
5cloned.b.d.push(5);
// Original is unchanged: still 2
6console.log(original.b.c);
// Original array is unchanged: [3, 4]
7console.log(original.b.d);
// Cloned array has the new element: [3, 4, 5]
8console.log(cloned.b.d);

Output

2
[ 3, 4 ]
[ 3, 4, 5 ]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • .× 16
  • ;× 8
  • (× 7
  • )× 7
  • =× 5
  • :× 4
  • ,× 3
  • {× 2
  • }× 2
  • [× 1

More JavaScript examples at level 4

← JavaScript typing practice