Clone!

3 Ways to clone objects in JavaScript

Farzad YZ
Farzad YZ
Oct 1, 2017 · 3 min read

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.

Talk is cheap, show me the code

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#L1320
function isObject(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};

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));
}

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);
}

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 :)

Better Programming

Advice for programmers.

Farzad YZ

Written by

Farzad YZ

Senior Software Engineer @epicgames . formerly @futurice . Javascript, Typescript, React(native), International speaker. UI engineering, Statecharts, Reactivity

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade