Spread Operator inside a function

Spread Operator inside a function
0.0 0

#1

Tell us what’s happening:
I have a few questions about the code in this problem:
Can someone explain why we need to assign arr2 = […arr1] inside a blank function? I don’t think I’ve seen an empty function like that before.

Also, what does it mean when we say" let arr2; " — I’ve always seen an expression after a new variable name so I’m confused.

Thanks in advance for help!

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_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

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


#2

The odd function you see there is an example of an Immediately Invoked Function Expression (or IIFE)

You can read more about them here: https://developer.mozilla.org/en-US/docs/Glossary/IIFE

These IIFEs are called the second they’re created and don’t need a name, they’re very handy in combinations with closures, but that’s not essential to learn at this exact time so don’t worry about it for now

Using let x; just declares x in the given scope outside of the function, again this is to do with closures and scope. Variabels that have been declared once don’t need to be declared again, they can simply be assigned to, e.g. x = 5; rather than let x = 5;


#3

Thank you so much! That was very helpful