Use the Rest Operator with Function Parameters Need Help

Tell us what’s happening:
Why does the function () have parentheses first? And at the end of the code there is () and I still don’t understand where they came from.

If I don’t misunderstand the code above, it will become:
const sum = (funtion () {…}) (); And I still don’t understand this code very much

Your code so far


const sum = (function() {
  "use strict";
  return function sum(x, y, z) {
    const args = [ x, y, z ];
    return args.reduce((a, b) => a + b, 0);
  };
})();
console.log(sum(1, 2, 3)); // 6

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/77.0.126 Chrome/71.0.3578.126 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-the-rest-operator-with-function-parameters

What you’re looking at, namely this stuff:

(function() {
  ... some code here
})()

Is called an Immediately Invoked Function Expression, or IIFE for short. It’s a useful if somewhat dated technique for making modules in Javascript that hide private data, and FCC uses it in some of its challenges even when it doesn’t need to, such as this example. In this case, it’s the same as just defining the function sum the normal way.

Note that you never need to write or change an IIFE in your own code, they’re just leftovers from when the challenge was written.

A decent intro to IIFE’s can be found at http://adripofjavascript.com/blog/drips/an-introduction-to-iffes-immediately-invoked-function-expressions.html

1 Like

When ever you see a function in the following formats :

let funcName = (function (){

})();

let funcName = (function (){

}());

let funcName = !function (){

}();

let funcName = +function (){

}();

They are call immediately invoked function expressions (IIFE).
In the above forms, the return values of the functions are been assìgned to tge given variable “funcName”.

Take note, values can also be passed to IIFE as shown below.

let funcName = (function (a, b, c){
return a + b + c;
}(1, 2, 3)); // funcName = 6.

1 Like