() why we write function inside that?

Hi, I’m confused about the parenthesis, why coder writes their function inside parenthesis and what is the name of that, here we go.

const sum = (    function() {
    return args.reduce((a, b) => a + b, 0);
} ) ();

Or

const sum = ( function() {
  "use strict";
  return function sum( ...rest ) {
    const args = [ ...rest ];
    return args.reduce((a, b) => a + b, 0);
  };
}) ();

the answer will be appreciated!

The code snippets you referenced are examples of what are called Immediately Invoked Function Expressions, or IIFE. The basic idea is that you create an anonomous (unnamed) function and then immediately execute it.

This may seem rather pointless at first glance, but the usefullness of this becomes more apparent once you understand how scope works in JS.

Wrapping your code in an IIFE is a classic way to isolate your code. Consider the basic script below:

const message = 'hello world'
console.log(message)

In this example, we have created a global variable called message. This works fine, but may cause problems if an additional variable by the name of message is used later on in our script, or in the script of a library that also creates global variables. This can be corrected by using an IIFE:

(function() {
  const message = 'hello world'
  console.log(message)
})()

Now the function works as before, but isolates the message variable from global scope, reducing the risk of unintended site effects.

This pattern is useful to know, but module bundlers like webpack will limit the scope of a files variables on default.

You can read more about IIFE here:

1 Like