JavaScript 30- Day 14 Study Notes
Day 14 of JavaScript 30 by Wes Bos covered the fundamental difference between reference as opposed to copy. These concepts explain one of the weird aspects of JavaScript behavior.
The code was pretty simple but demonstrated the concept.
let age = 100;let age2 = age;console.log(age, age2); //100,100age = 200;console.log(age, age2); //200,100 will not update 2nd variable
This is because, for strings, numbers, and booleans, a copy is made. So when we change a variable on the copy, the original is not changed.
An array, however, behaves differently.
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];const team = players;console.log(players, team);// ['Wes', 'Sarah', 'Ryan', 'Poppy']
However, if we change the 2nd array:
// You might think we can just do something like this:team[3]= 'Lux'; console.log( team);//['Wes', 'Sarah', 'Ryan', 'Lux']// updates original array as wellconsole.log( players); //['Wes', 'Sarah', 'Ryan', 'Lux']
This is because team[3] is a reference to players[3], not a copy.
So how to make a copy instead?
const team2 = players.slice();
This will make a copy of players[]. Now when we update team2[], the original array will not be changed. An interesting tip that when we don’t pass anything through slice(), it will copy the entire array.
Of course, in JavaScript, there is always more than one way of doing something.
const team3 =[].concat(players);
Concatenating will also make a copy.
So will using the spread operator.
`const team4 = [...players];
One more way of doing the same thing.
const team5 = Array.from(players);
Objects behave the same way.
const person = {name: 'Wes Bos',age: 80};const captain =person;captain.age = 99;//Now, person.age = 99
Because captain.age makes reference to person.age.
Making a copy instead.
const cap2 = Object.assign({}, person, {age: 99});
The final concept is this behavior only extends one level deep in objects.
const wes = { name: 'Wes', age: 100, social: { twitter: '@wesbos', facebook: 'wesbos.developer' }}const dev = Object.assign({}, wes);//makes copy
However:
dev.social.twitter = '@coolman';console.log(dev.social); //object {twitter:'@coolman, facebook:'wesbos.developer}console.log(wes.social);//object {twitter:'@coolman, facebook:'wesbos.developer}
At the 2nd level of the object, a copy is not made. Bos told us there is no straightforward way to work around this if we wanted to make a copy at a deeper level of an object. He gave us one way of doing it.
const dev2 = JSON.parse(JSON.stringify(wes));
This turns it into a string and immediately turns it back into an array. Bos didn’t particularly recommend doing this.
Follow my study notes as I progress through JavaScript 30.