JS Anonymous Functions

JavaScript Anonymous Functions

So far, every time we have created a function, we have given it a specific name. However, JavaScript also allows us to create functions without names.

A function without a name is called an Anonymous Function.


Named vs. Anonymous Functions

To understand the difference, let's first look at a standard, non-anonymous (named) function:

function doingStuffAnonymously() {
    console.log("Not so secret though.");
}

Here is how we turn that exact same function into an anonymous function by simply removing its name:

function () {
    console.log("Not so secret though.");
};

As you can see, our function has no name. It is completely anonymous. But this brings up an important question: If it has no name, how do you invoke (call) it?

Well actually, you can't invoke it exactly like that!


Storing Functions in Variables

In order to call an anonymous function, we have to store it inside a variable. This is possible because in JavaScript, functions are treated as values (just like a number or a string).

We can store our anonymous function in a variable like this:

Anonymous Function Variable

let functionVariable = function () {
    console.log("Not so secret though.");
};

// Calling the anonymous function using the variable name functionVariable();

Once stored, the anonymous function can be easily called by using the variable's name followed by parentheses: functionVariable();.

It will simply output: Not so secret though.


Why Use Anonymous Functions?

Creating a function just to immediately assign it to a variable might seem a bit useless at first glance, but it is actually a very powerful JavaScript construct.

Treating functions as variables enables us to do very cool things, like passing functions in as parameters to other functions. This concept adds another abstract and highly flexible layer to coding.

This specific concept of passing functions around is called using Callbacks, and we will discuss it in detail in the next section!


Exercise

?

If you create an anonymous function and assign it to a variable named mySecretFunction, how do you execute it?