0

I am dealing with this example of Javascript code:

    const real_numbers_array = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];

        //Karkoli že je increment, sedaj postane funkcija.
        const increment = (
            function(){
                //Namesto zgornjega "function()" dobimo "increment" 
                return function increment (a1,a2 = 1){
                    return a1 + a2;
                }

        })(); 
        console.log(increment(5,2));
        console.log(increment(5));

Where we have a constant increment to which we assign an anonymous function function() which returns function increment() with two arguments of which second has a default value and those two arguments are summed up.

So far I understand this. But at the end there is })(); and I don't know what is the meaning of the last empty ().

By default this code returns this:

enter image description here

And if I omit the () I get:

enter image description here

So what is the point of () at the end? Does anonymous function function() actually return only increment and we add () to get increment(). If this is so, why doesn't anonymous function return function as increment(). This is a default notation for functions afterall...

Is this some sort of an arrow function treachery? =)

71GA
  • 1,132
  • 6
  • 36
  • 69
  • 1
    It is a IIFE (immediately invoked function expression) it runs as soon as it's defined. `()` it creates a function expression through Javascript engine interpret the function and returns the output. – Abhishek Dec 14 '19 at 05:53
  • 1
    this question provided the details: https://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript but I also don't know why this functions requires it, I don't think it is necessary in this particular case – Surely Dec 14 '19 at 05:54

2 Answers2

1

IIFE (Immediately Invoked Function Expression)

The function expression () at the end will immediately invoked the function through which the JavaScript engine will directly interpret the function.

Mamun
  • 66,969
  • 9
  • 47
  • 59
1

const num1 = 1, num2 = 2;

const calculateSum = (function (n1, n2) {
    return n1 + n2;
})(num1, num2);

console.log(calculateSum); // 3

You can pass arguments to the function expression inside ().

Abhishek
  • 382
  • 1
  • 6