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 object1const original = { a: 1, b: { c: 2 } };// Object.assign creates a SHALLOW copy// Nested objects are still referenced, not copied2const shallowCopy = Object.assign({}, original);// JSON.parse(JSON.stringify()) creates a DEEP copy// All levels are fully copied3const deepCopy = JSON.parse(JSON.stringify(original));4 // Modify the nested value in original5original.b.c = 99;6 // Shallow copy shares the nested object, so it's also 997console.log(shallowCopy.b.c);// Deep copy is independent, still has the original value 28console.log(deepCopy.b.c);// Original was modified to 999console.log(original.b.c);Output
99 2 99
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