Use the Rest Operator with Function Parameters (Integrating arrow function)

Tell us what’s happening:
I tried to write the code with Arrow function but when I change it, the code doesn’t work like it should.

May someone show me to integrate the arrow function to the first line of the code?

Your code so far


const sum = (function() {
  "use strict";
  return function sum(...args) {
    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; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

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

Do you mean like this?

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

It works, but I try to understand what those parentheses do after the keys, before the semicolon.

})();

I think the parentheses () before the semicolon have the effect that the function gets called, so it actually starts executing. If you make a normal function:

function sayHi() {
  console.log('Hi');
}

you would call this function by typing its name followed by parentheses:

sayHi();

So, similarly, if you want to call a function that is made with the construction const x = function() {}, you put parentheses after it to call it.

This seems to be explained in a challenge later on in the curriculum, in the Object Oriented Programming section: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife/. Except here it is not stored in a variable.
I find it quite confusing that fcc uses code constructions that have not been explained yet, in earlier challenges. Especially when it is not necessary for the challenge - this particular challenge is about the rest operator and has nothing to do with how the function is called. I don’t know why fcc does it this way. If someone can explain this better, I would be grateful. I find it difficult to understand why there are two functions (and two ‘sum’ things?) and the whole thing is not written like this, instead:

"use strict";
const sum = function (...args) {
  return args.reduce((a,b) => a+b, 0);
};
console.log(sum(1,2,3));

sandrab

1 Like

because when it was necessary to activate strict mode to have error messages (instead of silent failing of the code), it was also necessary to have a closed environment in which to activate the mode , so the IIFE is there to create closure

now it is no more necessary so it is being removed from challenges, most challenges should be changed with next curriculum update

1 Like