Use the Spread Operator to Evaluate Arrays In-Place question

Because I wasn’t clear enough. Let me try again and split it up this time

When you assign a variable to another variable, it will be passed as a reference or as the value. This is a more complex topic, so let’s just agree that assigning a variable to an array only passes the reference. That means

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
const arr2 = arr1 // assigned the reference to the same array

console.log(arr1 === arr2) // true

Here what we are saying is that arr2 is equal to arr1. Not that the values are equal, but that the actual arrays are the same. Try this in the console and you’ll see they are in fact the same

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
const arr2 = arr1 // assigned the reference to the same array

console.log(arr1 === arr2) // true

arr1[0] = 'I was mutated!'

console.log(arr1[0]) // I was mutated!
console.log(arr2[0]) // I was mutated! -- oh no, arr2 was changed also!

Now the spread operator returns a new copy, with all the same values of the original

So let’s try that out

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
const arr2 = [...arr1] // assigned to a copy of arr1 values

console.log(arr1 === arr2) // false

arr1[0] = 'I was mutated!'

console.log(arr1[0]) // I was mutated!
console.log(arr2[0]) // JAN -- yay arr2 has not changed!

Tell me if something is still not clear and I’ll try to find another method.

9 Likes