Menu Close

Copy vs Reference in Javascript

Copy vs Reference in Javascript

Have you ever try to copy the value of an array and realized that new variable that you assigned is actually not a copy but a reference.
Sometimes we are intended to copy the value of an array or an object and apply the same method that we do to copy a normal string or a number like this:

let a = 1
let b = a;
console.log(a, b) // will return 1 1
b = 2
console.log(a,b) // will return 1 2
Enter fullscreen mode

Exit fullscreen mode

but if we try this it does not copy the value of array or object but instead create a reference and then whenever we try to change the value of second variable, the value of first one also changed like this:

const players = ['Wes', 'Rahul', 'Sarah'];
const team = players
console.log(players) // ['Wes', 'Rahul', 'Sarah']
console.log(team) // ['Wes', 'Rahul', 'Sarah']

team[2] = 'raj'
console.log(players) // ['Wes', 'Rahul', 'raj']
console.log(team) // ['Wes', 'Rahul', 'raj']
Enter fullscreen mode

Exit fullscreen mode

So in above code as we see, when we change the value of “team[2]”, value of “players[2]” also changed. and same case is with objects, like this:

const person = {name:"Rahul", age:"21"}
const captain = person

captain.score = 50

console.log(person) // {name:"Rahul", age:"21", score:50}
console.log(captain)// {name:"Rahul", age:"21", score:50}
Enter fullscreen mode

Exit fullscreen mode

that is second variable become a reference of first one;

But than how to copy them?

Well here are some methods to do so:
for arrays:

  1. using .slice()
  2. using .concat()
  3. using ES6 methods
  4. using Array.from()

for objects:

  1. using Object.assign()
  2. using JSON.parse(JSON.stringify())

Implementation:

1).
For Arrays:
Implementation of how to copy an array

2.)
For Objects:
i) Using Object.assign():-
It will take 3 parameters:-

  1. an empty object in order to copy
  2. Object whom which we want copy
  3. (optional) If we want any property to insert.

Implementation of Object.assign()

ii) using JSON.parse( JSON.stringify() ) :-

Implementation of JSON.parse( JSON.stringify())

Follow/DM me on Twitter for any help/collab

View Source
Posted in JavaScript