Tell us what’s happening:
I’ve solved the challenge, but I am uncertain what the fundamental difference is between my first solution:
newArr.push(arr)
and the solution that is expected (other than it uses the spread operator):
newArr.push([...arr])
Both lines return an array of arrays, and I can’t see any difference in the outputs. I’d like to know what the difference is that the spread operator provides. I’ve tried looking into it myself, but I can’t find anything concrete.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator
The difference is the first does not push a reference to a new copy of arr into newArr. Instead, it pushes a reference to arr into it.
To see the difference you can do run the two following code snippets:
const arr = ['a', 'b', 'c'];
const newArr = [];
newArr.push(arr);
console.log(JSON.stringify(newArr)); // [["a","b","c"]]
arr.push('d');
newArr.push(arr);
console.log(JSON.stringify(newArr)); // [["a","b","c","d"],["a","b","c","d"]]
and
const arr = ['a', 'b', 'c'];
const newArr = [];
newArr.push([...arr]);
console.log(JSON.stringify(newArr)); // [["a","b","c"]]
arr.push('d');
newArr.push([...arr]);
console.log(JSON.stringify(newArr)); // [["a","b","c"],["a","b","c","d"]]
In the first one, since you are pushing a new value to arr and you push “d” to it later, both subarrays of newArr have the values. Why? Because the reference the exact same array in memory. In the second one, when the sub arrays are not the same arrays as arr. They are copies which are stored in separate memory locations.
2 Likes