Need explanation of functions that returns same function

Need explanation of functions that returns same function
0

#1

This question doesn’t concern a specific challenge because it appears in many challenges, but I don’t quite understand the logic behind it.

Take for example this:

const sum = (function() {
return function sum(a,b) {
return a+b
};
})();
sum(2,5); // Results 7

Can someone explain what is that? Why is that different than this:

const sum =(function(a,b) {
return a+b;
}
)();
sum(2,5); // I get the following: Uncaught TypeError: sum is not a function

Also, I noticed the second function (the one being returned) has the same name as the const, does that has any significance or something? Is it the same as these 2 cases?

Case1:

const test = (function() {
return function sum(a,b) {
return a+b
};
})();
test(2,5);

Case 2:

const sum = (function() {
return function test(a,b) {
return a+b
};
})();
sum(2,5);

I have seen this function-returns-function-returns-something thing in a few challenges so far and I have no idea what this is and I feel like I’m missing something important here.

Thanks in advance


#3

The code you’ve posted is pure a redundancy.

// Example A
const fn = (function() {
    return function whatever() {
         return 1
    }
})()

The above function roughly reduces to this form

// Example B
const fn = function whatever() {
    return 1
}

How? The no-name function assigned to fn is immediately called returning the whatever() function. So, this whatever function is assigned to fn.

The name of whatever() doesn’t really matter because the only way to reach that function is via fn. Hence, it is often omitted when used in this context.
(What good is an identifier if it can’t be identified elsewhere?)

So, functionality-wise, there is no difference between example A and B. Thus, your Case 1 and Case 2 is identical as well.

@hbar1st mentioned these functions are recursive functions. However, they are not. By definition, recursive function calls themselves. However, do you see the function calling itself anywhere? there is no recursion happening in the given code.

What I can say is that the code you’ve posted is a redundant usage of IIFE.

Immediately Invoked Function Expression is a function that is immediately called at their declaration.
For example,

let foo = (function() {
    // foo's scope

   return something // something is assigned to foo
})() // () calls immediately

The surrounding (..) treats the function as an expression and the immediately following () operator calls it. So, the value assigned to a variable is anything returned from the outer-most function. It is often used to create a custom local scope such as mimicking module. This is IIFE in nutshell.