====== Mutating Data ======
JavaScript has somewhat annoying rules on this. Deep copies are required if you wish to avoid mutating.
----
const one = [0, 1, 2];
const two = one;
two.push(3);
console.log(one);
console.log(two);
output:
[ 0, 1, 2, 3 ]
[ 0, 1, 2, 3 ]
Note: slice works on arrays of primitives not objects
const one = [0, 1, 2];
const two = one.slice();
two.push(3);
console.log(one);
console.log(two);
output:
[ 0, 1, 2 ]
[ 0, 1, 2, 3 ]
But objects will still refer to the original arrays even with slice
const one = [
{
name: 'kalen',
age: 23
},
{
name: 'kailyn',
age: '22',
}
];
const two = one.slice();
two[0].name = 'Patrick';
console.log(one);
console.log(two);
output:
[ { name: 'Patrick', age: 23 }, { name: 'kailyn', age: '22' } ]
[ { name: 'Patrick', age: 23 }, { name: 'kailyn', age: '22' } ]
----