Welcome Mary.
The new array arr2
doesn’t return a spread array: it’s an array which is identical to arr1
. Whereas:
const newArray = [1, 2, 3];
console.log([…newArray]); //returns 1 2 3, not [1, 2, 3]
It’s more accurate to say “references” rather than “returns”. I don’t understand your example - I can’t duplicated it. It may be something about how your console works. It also is what I would expect from console.log(...newArray);
so perhaps it a typo.
Here is some values that I get:
const arr = [1,2,3,4];
console.log(arr);
// [1, 2, 3, 4]
console.log(...arr);
// 1 2 3 4
console.log([...arr]);
// [1, 2, 3, 4]
const arr2 = [...arr];
console.log(arr2);
// [1, 2, 3, 4]
console.log(Math.max(arr2));
// NaN
console.log(Math.max(...arr2));
// 4
console.log(Math.max(arr2[0], arr2[1], arr2[2], arr2[3]));
// 4
The last two are basically the same thing. The spread operator is taking those values in the array and spreading them out one by one. If your friend asked you to hand her a dozen eggs you could hand her a carton (an array, all bundled up). But if you used the spread operator, you would pass her the eggs one by one.
let arr1 = arr2;
That is valid JS but it is not doing what you think it is doing. Realize that those two variables do not hold arrays of data, they hold memory addresses (references) that point to a location in memory that holds the array data. This would copy the reference so you would have two variables pointing to the same location in memory. If you and your brother have the same address, that doesn’t mean that there are two houses.
Yes, it’s a bit weird and it commonly confuses people at first. It is the distinction between primitive data types (that behave like you’re expecting) and reference types (objects, functions, arrays, etc. … OK, technically in JS these are all just types of objects).
So, const arr2 = [...arr];
is a way to get a completely different array. You spreading out all those values: ...arr
. You are wrapping them in a new array: [...arr]
. And then then you are storing them into a new variable arr2
. This will create two independent variables referencing two independent places in memory that just happen to (for now) hold the same numbers. What you suggested would be two variables pointing to one place in memory so changing one would also change the other.
Yes, this is weird, but keep at it and you’ll get it.