Object.assign Clone in JavaScript

Level 4248 keystrokes

Compares shallow copy with Object.assign vs deep copy with JSON methods.

JavaScript code

// Create an object with nested object
1const original = { a: 1, b: { c: 2 } };
// Object.assign creates a SHALLOW copy
// Nested objects are still referenced, not copied
2const shallowCopy = Object.assign({}, original);
// JSON.parse(JSON.stringify()) creates a DEEP copy
// All levels are fully copied
3const deepCopy = JSON.parse(JSON.stringify(original));
4
// Modify the nested value in original
5original.b.c = 99;
6
// Shallow copy shares the nested object, so it's also 99
7console.log(shallowCopy.b.c);
// Deep copy is independent, still has the original value 2
8console.log(deepCopy.b.c);
// Original was modified to 99
9console.log(original.b.c);

Output

99
2
99
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.

  • .× 14
  • ;× 7
  • (× 6
  • )× 6
  • =× 4
  • :× 3
  • {× 3
  • }× 3
  • ,× 2

More JavaScript examples at level 4

← JavaScript typing practice