0

I am learning JavaScript from freecodecamp and there is a function that I don't understand the meaning of the extra (), I will attach the code, sorry if this already been asked before

I know that I need to the () in order to get the outcome but I cannot explain the reason behind it

const sum = (function() {
  return function sum(...args) {
    return args.reduce((a, b) => a + b, 0);
  };
})(); //what I am asking is (func....)(); what is the reason behind those 2 ()?

console.log(sum(1, 2, 3, 4));

The outcome is 10, which I understand the function, I just don't understand the meaning behind it

  • What's even stranger is why even do this,. If the function sum was holding some sort of closure, then it would make sense. But as is, it's just a pointless IIFE. – Keith Jun 19 '19 at 15:18

1 Answers1

2

It's an IIFE (Immediately Invoked Function Expression) - it's a JavaScript function that runs as soon as it is defined.

https://developer.mozilla.org/en-US/docs/Glossary/IIFE

PaulB
  • 23,264
  • 14
  • 56
  • 75