0

in the following example of functions inside a constant I don't understand the presence of the two sets of round brackets, one containing the main function and the second one just on its own at line 5

 1  const increment = (function () {
 2    return function increment (number, value) {
 3       return number + value;
 4    };
 5  })();
 6  console.log(increment(5,2));

Getting rid of the brackets will not give an error but will print this instead of the result

ƒ increment (number, value) {
        return number + value;
}

I tried using just one plain function instead (as opposed to nested ones) and as expected no brackets were needed,

Finally, thinking that maybe the sets of brackets somehow needed to match the number or arguments of the nested function, I tried a similar constant declaration but with three arguments to see whether I needed as many sets of brackets to go with it (example below) but as it turns out it only needed the same brackets as in the original bit.

const sum = (function () { 
    return function sum1(a,b,c)  { return a + b + c};
})();
console.log (sum(1,2,3));

Not sure whether I've missed something obvious or there are syntax rules I'm not aware of. Either way, if anyone can help it would be greatly appreciated.

Thank you

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
  • Since you're asking about javascript, you should use the 'javascript' tag. – Paul Dempsey Mar 16 '23 at 18:25
  • Fair point @PaulDempsey, fixed – lorenzo tamiazzo Mar 16 '23 at 18:39
  • "*maybe the sets of brackets somehow needed to match the number or arguments of the nested function*" - no, the need to match the number of argument of the outer function. – Bergi Mar 16 '23 at 18:54
  • "*I tried using just one plain function instead (as opposed to nested ones) and as expected no brackets were needed*" - yes, the nesting is really pointless here. Where did you get this example from? – Bergi Mar 16 '23 at 18:55
  • @Bergi I got it from this video at about 2:53:30 https://www.youtube.com/watch?v=PkZNo7MFNFg Yes the nesting is pointless as it's just functional to something that is shown later in the video. It's just frustrating not understanding the logic behind those round brackets. It does not work without them Thank you for your replies by the way – lorenzo tamiazzo Mar 16 '23 at 19:36
  • Duplicate of https://stackoverflow.com/questions/26092101/what-is-this-javascript-pattern-called-and-why-is-it-used – Paul Dempsey Mar 16 '23 at 21:35
  • @PaulDempsey it already is closed as a duplicate of that question… – Bergi Mar 16 '23 at 22:00

0 Answers0