
Primitive and referenced values (objects) behave very differently when we want to make a copy of them.
Primitive values
Let's suppose a variable name that has a primitive value associated with it (number, string, boolean, undefined and null). If we make a copy of this variable name to another variable name2, any modification in the original variable will not imply any change in the second variable as they are primitive values.
let name="Silvia"; let name2=""; console.log (name, name2); // returns Silvia, Silvia name="Luigi"; console.log (name,name2); // returns Luigi, Silvia
Example 1
Values by reference
However, if we do the same operation on values by reference, any change we make in one of the variables will also be reflected in the other variable since both variables point to the same object. (see example 2)
Arrays
To clone arrays, the slice()
method is used to create a new copy of the array. This copy can be modified independently without affecting the original array (n3 example 2). If no parameters are passed, it makes an exact copy of the array, but numbers can also be passed as parameters. If only one number is passed, it will determine the value of the index from which we want the copy to be made, while if 2 numbers are passed, we will be marking the beginning and the end.
//n.1 const names= ['Silvia','Luigi','Alex']; const names2= names; console.log (names, names2); // returns name ['Silvia','Luigi','Alex'] // returns names2 ['Silvia','Luigi','Alex'] //n.2 names2[2]="Angelo"; console.log (names,names2); // returns name ['Silvia','Luigi','Angelo'] // returns names2 ['Silvia','Luigi','Angelo'] //n.3 const name2= names.slice(); names2[2]="Anna"; console.log (name2,names2); // returns name ['Silvia','Luigi','Angelo'] // returns names2 ['Silvia','Luigi','Anna']
Example 2
Objects
The same happens when the referenced value is an object, any modification in one of its properties will affect both variables (n.2 Example 3). To clone objects, the Object.assign() method is used, which will copy the values of all enumerable properties of one or more source objects to a target object (n.3 Example 3). But this method is only effective for shallow copies of objects, i.e. when our starting object has no other objects as attributes.
//n.1 const names= { name:'Silvia', surname:'White' } const names2= names; console.log (names, names2); // they are exact copies //n.2 names2.surname='Green'; console.log (names,names2); /* returns const names= { name:'Silvia' surname:'Green' } returns const names2= { name:'Silvia'; surname:'Green'; } */ //n.3 const name2= Object.assign({}, names); names2.surname="Green"; console.log (names,names2); /* returns const names= { name:'Silvia' surname:'White' } returns const names2= { name:'Silvia' surname:'Green' } */
Example 3: Cloning of objects at first level
To make a deep copy of objects other methods are used.
As we said, the Object.assign()
method was only valid when we were trying to make a shallow copy of the object, that is, when our object does not have other objects as attributes. In these cases, a deep copy of the object is necessary.
A deep copy, unlike a shallow copy, also copies each sub-object recursively until all the objects involved are copied.
What methods can we use for a deep copy of Objects?
JSON.parse(JSON.stringify(obj))
This method converts the object to a string with JSON.stringify() and then converts it back to a JSON.parse() object. This method is effective with simple objects but not when one of the properties is a function (Example 4).
//n.1 const names= { name:'Silvia', surname:'White', social: { twitter: '@manoweb', facebook:'ManoWeb' } } const names2= JSON.parse(JSON.stringify(names)); names2.social.facebook='manoagency'; console.log (names, names2); /* returns const names= { name:'Silvia', surname:'White', social:{ twitter:@manoweb facebook:'ManoWeb' } } returns const names2= { name:'Silvia', surname:'White', social:{ twitter:@manoweb facebook:'manoagency' } } */
Example 4
Exploiting recursive functions in Deep Clone
Another very interesting and elegant way to make deep copies of objects is to use recursive functions (Example 5).
We create a function deepClone(object)
to which we pass as an argument the object we want to clone.
Inside the function, a local variable clone is created, which is an empty object where each of the properties that will be cloned from the starting object will be added.
Thanks to a for
we go through each and every one of the properties of the object we want to clone.
- If the property is not an object, it is simply cloned and added to the new clone object.
- If the attribute is an object, the deepClone(value) function is executed again, passing the value of the property (in this case the object) as a parameter, and the same process is repeated.
function deepClone(object) { var clone={}; for (var key in object) { var value = object[key]; if (typeof(value)!='object') { clone[key]=value; } else { clone[key]=deepClone(value);//Here the object property is also an object. //By means of a recursive function, what we do is to clone the object that //is on the second or next level. } } return clone; } deepClone({value1:1,value2:{value3:2}}); //{value1:1,value2:{value3:2}} deepClone({value1:1,value2:{value3:{value3b:3}}}); //{value1:1,value2:{value3:{value3b:3}}}
Example 5

Luigi Nori
He has been working on the Internet since 1994 (practically a mummy), specializing in Web technologies makes his customers happy by juggling large scale and high availability applications, php and js frameworks, web design, data exchange, security, e-commerce, database and server administration, ethical hacking. He happily lives with @salvietta150x40, in his (little) free time he tries to tame a little wild dwarf with a passion for stars.
Related Posts
How to use the endsWith method in JavaScript
In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…
What are javascript symbols and how can they help you?
Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…
Callbacks in JavaScript
Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…
How to create PDF with JavaScript and jsPDF
Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…
How to make your own custom cursor for your website
When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…
Node.js and npm: introductory tutorial
In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…
How to connect to MySQL with Node.js
Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…
JavaScript Programming Styles: Best Practices
When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…
Difference between arrow and normal functions in JavaScript
In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…
JavaScript Arrow functions: What they are and how to use them
In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…
How to insert an element into an array with JavaScript
In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…
What is the difference between primitives types and objects in JavaScript?
In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…