Use the Spread Operator to Evaluate Arrays In-Place, pointless?

Use the Spread Operator to Evaluate Arrays In-Place, pointless?
0.0 0

#1

–> https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place

The whole point of this challenge is to copy the array arr1 to arr2 in place w/ spread operator.

'use strict';
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2 = [...arr1]
console.log(arr2)

This seems all too pointless, as you can just do:

let arr2 = arr2

While is the same thing without spread operator.

The explanation of this use of the spread operator is in the challenge seems very weak and vague. Can someone please better explain what the use is?


#2

It isn’t passing by reference, it’s a new copy, whereas arr2 = arr1 is just saying arr2 are the same a. It’s the same as creating a copy using slice(), but generally a bit clearer as to intention.


#3

I think the best way is to discover it by trying it yourself.
See what happens if you define arr1 as follows:

const arr1 = [‘JAN’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’];

Then do what you propose:

let arr2 = arr1

Then do what the excercise tells you to:

let arr3 = […arr1]

Now push a new item into arr2 and arr3

arr2. push(“arr2 push”);
arr3.push(“arr3 push”);

and finally print arr1 to your console.log

console.log(arr1)


#4

Wow i never knew that happened, thanks :smiley:

Basically a new copy without changing the previous array :open_mouth:


#5

The solution is pretty easy , all you have to do is copy arr1 spread using rest operator into arr2 ;

like here :

arr2 = […arr1];

And the solution is solved.