It is a function that does not have a name or one that has been hidden out of scope around its creation.
In the below code block, we define one variable and two functions.
Now, how do we wrap this in an anonymous function? Simply!
We can see that anything that lives within the following block becomes an anonymous function:
Ok, this works pretty well, but we are not able to access it anymore if we ran this code. So how do we do this?
Note the important addition of the
(window) caller at the very end of this example. Along with the
w variable being assigned in the first line of the caller function.
You can pass as many parameters as you like, as long as you register them in the caller function.
So far our example works but seems a little useless. So instead we will try and create something more useful:
Now we can use it outside of this anonymous function as:
Because it’s bound to the
window object, we could actually just call it as follows:
This is ideal as now we have a decent way to package a list of variables and functions under a namespace called
our_unique_object. This could be your company or project name.
If you’ve been following along, we don’t actually make use of the
w variable we pass in, so we can either use it, or get rid of it, let’s do the latter, but keep our caller:
Multiple Levels of Anonymous Functions
As you have probably guessed, it’s possible to have multiple layers of Anonymous Functions:
Let’s try and use this:
“Uncaught TypeError: b is not a function”
This is interesting! It immediately evaluated the
a variable with the input value, because we added the
If we made a change as follows (to not automatically evaluate it):
And tried to run it:
This is because we have lost our
input scope due to the nature of anonymous functions and the event loop.
We now need to call the function ourselves with some input data of our own.