Spread operator example

Tell us what’s happening:

Hi, I’m not following the solution presented. I understand the assignment of the spread operator (i.e. between the brackets). What I don’t understand is:
a. the use of the function
b. the use of “use strict”
c. the extra use of parentheses to wrap the function
d. the extra use of parentheses at the end (outside) of the function

Any explanations on each of the above is greatly appreciated.

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

Challenge: Use the Spread Operator to Evaluate Arrays In-Place

Link to the challenge:

Hello there.

  1. The function serves 2 purposes:
  • Limit the scope of the variables within (not in this case, but it is common)
  • Create a separation of code, mostly for structure.
  1. ‘use strict’ - useful information
  2. Your c and d are linked to my 4
  3. This function is called an IIFE (Immediately Invoked Function Expression). It is wrapped inside parentheses so that the outside parentheses can have a scope to invoke. Here is an example:
// THESE TWO ARE PRACTICALLY THE SAME
function myFunc() {
  //Do stuff
}
myFunc();
//----------------------
(function() {
  //Do stuff
})();

Hope this helps

Thank you. Let me ask another way. Why couldn’t you just put…

arr2 = [… arr1];

In other words, why not just assign it without the function?

Well, in this case, I guess mostly readability, and ease of typing. If you want to re-use the value multiple times, make it shorter/consistent. This code is not practical; it serves to show how you might find the use-case.

In this case, the only thing the function is doing is limiting the scope of 'use strict'.

Thank you! I have some more learning to do.