Updated: Jun 17, 2018
We all knew about anonymous functions before, but we purposefully didn’t use them. Our experience with passing around functions as arguments was that of hard to read and hard to debug code. To battle these shortcomings we reduced to a minimum our usage of function arguments. Where they had to be used we adopted a very verbose strategy. For example, when handling events, we’d create a skeletal event handler that simply called the function that does all the action, thus augmenting readability.
The case for Anonymous functions
An Asynchronous action is a piece of code that executes independently of your normal application flow. Common asynchronous scenarios are a need to call a server, a need to delay an action, wait for some resource to load, etc.
Here’s a simple piece of code, that synchronously creates a list of buttons from some sort of a description class.
Now, let’s see how the same code can be written using an anonymous function:
In other words, it is often the case with asynchronous actions that the context in which I want to execute the delayed action is the same context in which I executed the original action. Anonymous functions let me keep that context.
Anonymous functions are a great tool to bridge the gap when we have an unnatural context switch. If we find that the callback function is a natural extension of the original function, or that we have to pass around or store many of our local variables in order to recreate the context in which we previously existed, it may be the case that an anonymous function will do the trick more elegantly.