Friday, January 20, 2017

JS30 Challenge Day 14 - Copy and Reference

Github Link

1.Copy
let age=100;
let age2=age;
age2=200;
age will not change to 200

If age is changed, age2 will not change

2.Reference
players and teams are arrays
const team = players;
team[3]="AK";
Here, players[3] also changes to AK

If players is changed, team also changes. So this changes the values both ways.

3.Copy
const team2=players.slice();
changing team2 will not affect players

Changing either one won't change the other
Works for [...players] and Array.from() the same

4.Reference
Just like arrays, objects also pass by reference
To avoid that, we use Object.assign();

const age3=Object.assign({},person,{number:99});
first arg is an empty object, second is the object to fold in, third is the values we want to additionally fold in.
Difference between slice and splice in Arrays

No comments:

Post a Comment