Use the Spread Operator to Evaluate Arrays In-Place

Use the Spread Operator to Evaluate Arrays In-Place
0

#1

Here it the right answer, i did it, but i don’t get it !
Why not just [arr] instead of […ar] ?? I don’t understand the spread concept

Your code so far


const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
  "use strict";
  arr2 = [...arr1]; // change this line
})();
console.log(arr2);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:60.0) Gecko/20100101 Firefox/60.0.

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


#2

When you use […arr1] you copy the elements (it is a shallow copy, though, be careful if the elements aren’t basic types). The result is [ ‘JAN’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’ ].

But [arr1] creates something very different [ [ ‘DEC’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’ ] ], an array inside another array.

Try it in a node console. You’ll see something like this:

> const arr1 =  ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
> let arr2 = [...arr1]

> arr2
[ 'JAN', 'FEB', 'MAR', 'APR', 'MAY' ]

> arr2[0] = 'DEC';
> arr2
[ 'DEC', 'FEB', 'MAR', 'APR', 'MAY' ]
> arr1
[ 'JAN', 'FEB', 'MAR', 'APR', 'MAY' ]

> let arr3 = [arr2]
> arr3
[ [ 'DEC', 'FEB', 'MAR', 'APR', 'MAY' ] ]

#3

Hi, I am not understanding Spread Operator either.

I understand that let arr2=[arr1] will return this:
[[ ‘JAN’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’ ]]

but
let arr2 = arr1 returns the same result as arr2= […arr1].
So why we should complicate…? Can you explain more simply… What is the difference, cause the result is the same to me…
Regards


#4

I finally got the grasp of […arr1] but what I was missing was instead of just let arr2 or const arr2 I needed to return arr2 =

That then passed the challenge.