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


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]

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?

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.

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



Wow i never knew that happened, thanks :smiley:

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

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.

I came up with this solution because I did not understand what the test was asking for. Based on the example and what I read around the internet, I thought this was the best solution. However, it claims I did not use the spread operator despite the copy to arr2:

const arr1 = [‘JAN’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’];
let arr2 = (function(month1, month2, month3, month4, month5) {
“use strict”;
return [month1, month2, month3, month4, month5]; // change this line

I know it is kinda out of the box but this is what I thought needed to be done.

This was a great way to explain the concept. It went straight into my notes :slight_smile: