How to Actually Copy an Object & Not Only Reference It

Mehak BaharMehak Bahar
2 min read

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

0
Subscribe to my newsletter

Read articles from Mehak Bahar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mehak Bahar
Mehak Bahar

Hey there! I'm Mehak Bahar, navigating the tech world and sharing the real deal over. Think of this space as my tech diary, where I spill the beans on the highs and lows. Currently knee-deep in web development and design, I'm all about sharing the nitty-gritty - from coding mishaps to those 'aha' moments. But it's not just about tech glitches; I've got my eyes set on the AI realm too. This journey is more than just lines of code; it's a ride filled with challenges, victories, and a sprinkle of geeky fun. So, fellow tech enthusiasts, let's dive into this adventure together!