In this lesson I learned about the differences between a reference and a copy in JavaScript.
Strings, numbers and booleans all update as they are set.
With arrays[], if you create a reference to an array (team[] = family[]) as you update the reference 'team', it will also update the original array 'family'.
Instead of referencing the array, it can be copied. One way to do this is by passing an empty .slice() (team = family.slice()).
- Or you can create a new array and concatenate in the old one (team = [].concat(family)).
- Or you can use the new es6 ... spread (team = [...family]).
- Or you can use the Array.from() method (team = Array.from(family)).
With objects{} it's the same as an array. You make a reference to the object by doing this (captain{} = person{}).
In-order to make a copy, you can assign a new object to the variable (Object.assign({}, person, { number: 99, age: 12 })).
Note: This only goes one level deep both for arrays[] and objects{}.
See the Pen
JavaScript30 - 14 - JavaScript References VS Copying by Corey Noble (@CoreyNoble)
on CodePen.