Can someone help me understand this?

I found this code in the beta.freecodecamp.org website.

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

Maybe some of you think that this is pretty normal, but i found something strange and very new to me.
Like, this;

What is this thing? => ( <= function() {
  ...
} => )() <= and what is this too?

I mean, I want to know what it means by adding this " ( " sign before the ‘function’ word. And why does it end with " ) (); ".
Does it make a difference with writing it like this?

function() {
 ...
};

What does that mean? Can someone tell me? It’s really new to me.

Hey @atindo23,
There are a couple of things to explain and I will explain them one by one.

  • When you wrap a function in parenthesis you are boxing it in its own scope.

  • There is a major difference between writing a function like this: function() { ... }; And writing a function like this: (function() { ... }); by the fact that the latter writing method is evaluated as a function expression and not a function declaration

  • () <= and what is this too? - This is the invocation of the function. Meaning, it gets executed immediately.

You can find a more elaborate explanation here:

1 Like