Talk is cheap, show me the code

Cloning an object in JavaScript a task that is almost always used in any project, to clone everything from simple objects to the most complicated ones.

As it may seem simple for not seasoned JavaScript developers, it actually has some pitfalls that would hurt you in the bones if you didn?t know the proper way to do it.

The first way that could cross a developer?s mind is to deeply iterate through a source object?s properties and copy them one by one on the target object. It may seem good at the beginning, but it is not a performance-friendly solution potential bottlenecks come when working with large or deep objects.

1: Deep copy using iteration

Note: To copy deeply, we need to recursively detect if the value is yet another object (object literal in this case, functions and arrays will be treated normally) or not.

// source: https://github.com/jashkenas/underscore/blob/master/underscore.js#L1320function isObject(obj) { var type = typeof obj; return type === ‘function’ || type === ‘object’ && !!obj;};function iterationCopy(src) { let target = {}; for (let prop in src) { if (src.hasOwnProperty(prop)) { // if the value is a nested object, recursively copy all it’s properties if (isObject(src[prop])) { target[prop] = iterationCopy(src[prop]); } else { target[prop] = src[prop]; } } } return target;}const source = {a:1, b:2, c:3};const target = iterationCopy(source);console.log(target); // {a:1, b:2, c:3}// Check if clones it and not changing itsource.a = ‘a’;console.log(source.a); // ‘a’console.log(target.a); // 1// Nested example!const x = {a: 1, b: {c: 1}};const y = iterationCopy(x);x.b.c = 2;console.log(y.b.c); // still “1”

So as you see, it?s working!

Now let?s cut the chase to the second solution which is indeed more elegant but, more limited to use.

2: Converting to JSON and back

function jsonCopy(src) { return JSON.parse(JSON.stringify(src));}const source = {a:1, b:2, c:3};const target = jsonCopy(source);console.log(target); // {a:1, b:2, c:3}// Check if clones it and not changing itsource.a = ‘a’;console.log(source.a); // ‘a’console.log(target.a); // 1

Note: Be careful about using this method as your source object must be JSON safe. So it may need some sort of exception handling to keep it safe in cases in which the source object is not convertible to JSON.

3: Using Object.assign

Update: This method has a flaw that it only does a shallow copy. It means that nested properties are still going to be copied by reference. Be careful about it.

This way is the best and the safest way I personally consume in my projects. It?s leveraging a built-in static method on the Object object and is handled and provided by the language. So use this one!

function bestCopyEver(src) { return Object.assign({}, src);}const source = {a:1, b:2, c:3};const target = bestCopyEver(source);console.log(target); // {a:1, b:2, c:3}// Check if clones it and not changing itsource.a = ‘a’;console.log(source.a); // ‘a’console.log(target.a); // 1

Conclusion

Every framework and library, such as Lodash and Underscore, have a way to support cloning objects. Almost all of them used a more complex version of iterationCopy before ES6 was introduced. On ES6+ environments, there is language support for Object.assign, so try to use the most out of it. As a rule of thumb, always try to use the 3rd solution and avoid the JSON solution.

Keep calm and clone objects without any hesitation 🙂

24