How to Actually Copy an Object & Not Only Reference It

How to Actually Copy an Object & Not Only Reference It

JAVASCRIPT TIPS & TRICKS

Consider of a case in JavaScript

var a = [1,2,3,4,5];
var b = a;
b.pop();
console.log(b);// output will be [1,2,3,4]
console.log(a);// surprisingly output will be [1,2,3,4]

The same is true with objects (as arrays themselves are a type of object).

But How?

This behavior is due to the fact that arrays as well as objects are reference types in JavaScript. This is because when you assigna = b , you are not creating a new array, but rather both 'a' and 'b' references to the same object in the memory. So therefore, when you apply b.pop();the array itself is affected so you get the modified value on printing both 'a' and 'b'.

Here Comes REFERENCE SEMANTICS

The concept discussed earlier is known as reference semantics or reference types. When you assign an object (including an array) to a variable or pass it as an argument to a function, in real you are working with a reference to it and not a copy of it. This is a distinction with the premitive types (such as numbers or strings), as in the same case, you will be dealing with a copy of the premitive types.


Now the question arises. HOW TO FIX THIS! There are two ways to copy an object without referencing it:

Spread Syntax

To resolve this issue, you can use spread syntax i.e. [...a] :

var a = [1, 2, 3, 4, 5];
var b =  [...a];
b.pop();
console.log(b); // Output: [1, 2, 3, 4]
console.log(a); // Output: [1, 2, 3, 4, 5]


.slice();

You can also use .slice(); to solve this problem:

var a = [1, 2, 3, 4, 5];
var b = a.slice(); 
b.pop();
console.log(b); // Output: [1, 2, 3, 4]
console.log(a); // Output: [1, 2, 3, 4, 5]

For queries and further assistance drop a comment