I have seen sometimes code like this in web pages:
function foo(left, right) {
return foo = function(l, r) {
return l + r;
}, foo(left, right);
}
What’s the point of doing this? why not just return left + right
?
It looks a bit like the idea of using a self-executing function, which is usually done to prevent namespace collisions, but what’s the point of doing it inside of a function declaration?
3
Answers
the example does seem a bit unconventional and may not have a clear advantage over a simple function implementation like directly returning left + right
but still This pattern can be powerful in certain situations but it’s not always necessary there reasons you might need to use this pattern optimization after initialization If the initial function needs to perform some setup that only needs to happen once this pattern ensures that setup happens on the first call and subsequent calls are optimized or you just want to allows a function to modify its own behavior after the first execution
I guess your example isn’t presentable. Usually declaring local function and returning it’s output is done for creating a closure to store the function’s arguments which are mutated otherwise. Usually that’s done with IIFE
In this example if you remove the IIFE the result would be not what you’d expect.
i
is passed as an argument and saved from mutation in the outer while loop. There could be different kinds of loops, variables to pass arguments (for example object references that could be reassigned) and other cases.This is a programming pattern called "function memoization" where a function, upon first call, performs something (often something time-consuming or computationally expensive), while also redeclaring itself on this first call.
This can be beneficial if the first call’s results can be cached and used in subsequent calls.
Imagine something like this, where a function is supposed to work on dynamic data retrieved from a REST endpoint, then answer questions on that data:
This may technically not be the most valid of examples since it suggests changing from
async
to sync, but it explains the idea. Another reason it’s not ideal for real-world application is that browsers would probably cache the response for you after the first call. Again, it’s just an example to understand the purpose of the pattern.Here’s an exhaustive article on the concept: https://www.freecodecamp.org/news/understanding-memoize-in-javascript-51d07d19430e/