Anonymous function without arguments return itself with arguments

Ankit Gupta :

I am learning javascript and have seen anonymous functions written like this without any explanation:

const sum = (function() {
    return function sum(x,y,z){
        return (x+y+z);
    };
})();
console.log(sum(1,2,3)); //6

The way I read it is: declare a function anonymously and assign it to the const sum. Call sum() with the parameters and console.log() the results.

This is very confusing to me as I don't understand why it is written the way it is. Some questions are:

How is sum accepting parameters when the outermost function has no parameters specified? Why are we not specifying the parameters on the outermost function?? Why is it returning itself and which 'sum' gets called when?

Apologies if it is too dumb or obvious. I have struggled a lot and have finally decided to ask here.

Abhay Sehgal :

First of all this function is not only anonymous. it's an iife (immediately invoking function) and it's returning sum function. So const variable sum is actually sum function that is returned by iife function.

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

So, in the above line sum is referring to the function sum returned by iife function not the iife function itself

For more understanding about iife check - https://developer.mozilla.org/en-US/docs/Glossary/IIFE

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302594&siteId=1