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
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']
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}
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:
- using .slice()
- using .concat()
- using ES6 methods
- using Array.from()
for objects:
- using Object.assign()
- using JSON.parse(JSON.stringify())
Implementation:
2.)
For Objects:
i) Using Object.assign():-
It will take 3 parameters:-
- an empty object in order to copy
- Object whom which we want copy
- (optional) If we want any property to insert.
ii) using JSON.parse( JSON.stringify() ) :-
Follow/DM me on Twitter for any help/collab