Anonymous function without arguments return itself with arguments

Viewed 515

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.

2 Answers

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

For better understanding, we can expand it to:

const _sum2 = function() { // anonymous function
    return function sum(x,y,z){
        return (x+y+z);
    };
}

const sum = _sum2(); // value of _sum2 returns
// it is the same as
const sum = function sum(x,y,z){
    return (x+y+z);
}
console.log(sum(1,2,3));

Test it yourself:

const sum = (function() {
    return function sum(x,y,z){
        return (x+y+z);
    };
})();
console.log('const sum = ' + sum.toString());

such syntax is used to protect intermediate valiables and functions. In your case there are no such variables, but:

const sum = (function() {
    const n = 10;
    function protected() {
        return n;
    }
    return function sum(x,y,z){
        return protected() * (x+y+z);
    };
})();
console.log(sum(1,2,3));  // evaluates to 60

function protected and variable n are sealed and not exposed to your global environment.

Related