The uses of parenthesis in a starting statement, starting with open parenthesis

Tell us what’s happening:
For example in this lesson:
ES6: Use the Spread Operator to Evaluate Arrays In-Place
They use code like this:

Your code so far
´´´

(function() {
  "use strict";
  arr2 = []; // change this line
})();

I don’t understand why they open a parenthesis out of the blue, put a function inside, close it and then open another parenthesis then close it, empty, without calling any functions or variables. And I have no idea how to search in the internet for that. It kind of shocks me the use of those parenthesis.

Please help.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; rv:66.0) Gecko/20100101 Firefox/66.0.

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

This is called an immediately invoked function expression (or IIFE for short). It’s basically a function that’s ran right on the spot.

Answer

The snippet in your question is self-executing, so it runs when you define. Traditionally, you define a function and then later in the code call the function.

Definition

An IIFE (Immediately Invoked Function Expression), pronounced as “iffy”, is a JavaScript function that runs as soon as it is defined.

(function () {
    statements
})();

It is a JavaScript idiom used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.

Breakdown

An anonymous function is a function without a function name:

function () {
    statements
};

You can also use parenthesis as a grouping operator ( ) like you use in a mathematical operations.

( /*<-- grouping operator opening*/ function() {
    statements
)/*<-- grouping operator closing*/ ();
(function () {
    statements
})/*-->*/()/*<-- this set of parenthesis cause the function within the group operators to self execute*/;

More Reading

References