Shallow Copying / Cloning Objects in JavaScript

Object.assign Method

Let’s create a person object and clone it with Object.assign in below example:

const person = {
name: 'john',
age: 35,
interests: { javascript: true }
};
const clone = Object.assign({}, person);console.log(clone);
// { name: 'john', age: 35, interests: { javascript: true } }
...person.name = 'jane';
person.age = 40;
person.interests.javascript = false;
console.log(person);
// { name: 'jane', age: 40, interests: { javascript: false } }
console.log(clone);
// { name: 'john', age: 35, interests: { javascript: false } }

Spread Operator ( ... syntax) Method

The spread operator comes with ECMAScript 2018 standard and is now supported by most modern browsers and NodeJS by default. Its usage is pretty and simple. Just replace the cloning line in the above example with the following:

const clone = { ...person };

Lodash Method

Most of the time it is a good idea to use a utility library in our applications. Although JavaScript has gotten more and more powerful over the years, its standard toolset does not cover all of our ambitious requirements. At this point, utility libraries join the action. Lodash is a popular choice. Here’s how it’s done in _ :

const _ = require('lodash');...const clone = _.clone(person);

Conclusion

We demonstrated 3 ways of shallow cloning:

Object.assign({}, person); // Old-school JS
const clone = { ...person }; // Spread operator
const clone = _.clone(person); // Lodash method

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store