How to Write Anonymous Functions in JavaScript

There are a number of different ways to write functions in JavaScript.

One of the types of JavaScript functions is called anonymous functions.

As its name suggests, an anonymous function is a function that is declared without a name. Said differently, an anonymous function does not have an identifier. Anonymous functions are usually arguments passed to higher-order functions.

In this tutorial, I will teach you how to write an anonymous function in JavaScript. You will also learn the many uses of anonymous functions and the advantages and disadvantages of using this function type in JavaScript.

Table of Contents

You can skip to any specific section of this JavaScript anonymous functions tutorial using the table of contents below.

What is an Anonymous Function?

An anonymous function is a function that is defined without a name.

Anonymous functions are not stored but are associated with a variable.

Similar to normal functions, anonymous functions can also accept inputs and return outputs.

An example of a simple anonymous function is as shown below:

var abc = function ()
{


}


The function is defined without a name. This anonymous function can be called by using the defined variable name.

abc()

Defining an Anonymous Function

We can define anonymous functions in any of the three ways described below.

  1. Anonymous function as an immediately invoked function expression

  2. Anonymous function assigned to a variable

  3. Anonymous function as an argument that is passed to another function

Anonymous function as an immediately invoked function expression:

Anonymous functions can be declared as a function expression that will be invoked immediately upon declaration.

Let us define a function called sqrt in the JavaScript console of the browser.

function sqrt(x) 
{
    return x * x;
}

If you call this function and pass a number into the function, it will return the square root of that number. For example:

sqrt(25) //This will return 5

This function had a name and hence we were able to reference it easily. Let us now define an anonymous function with the same functionality.

function (x) 
{
    return x * x;
}

Your browser now throws an error Uncaught SyntaxError: Unexpected token when you press enter.

Your browser threw an error because your function does not have a name and your browser did not know how to call your function.

Let’s now see how to write this anonymous function in a way that your browser understands.

function (x) 
{
    return x * x;
}
(5)

When you try running this JavaScript in your console, you will notice that it returns the function you called and uses 5 as an argument.

We’ll see a few more examples of anonymous functions that are invoked immediately upon declaration in the next several sections.

JavaScript Anonymous Function Example 1:

 (function (x) { return x * 5; })(3);

This anonymous function multiples its sole parameter by 5. In this case, the parameter is 3, so the function returns 15.

JavaScript Anonymous Function Example 2:

(function () 
{ return "Example of an anonymous function"; })
();

This anonymous function simply returns the string Example of an anonymous function.

JavaScript Anonymous Function Example 3:

(function (a, b) 
{ 
    var c = a + b; 
    return 4 + c; 
})
(5, 4);

This anonymous function returns the sum of its two parameters and 4. In this case, it returns 13, which is the sum of 5, 4, and 4.

In the examples above, it’s easy to understand that functions are anonymous functions.

They were all immediately invoked with what was present inside the evaluated function.

We’ll now consider an example of a more complicated anonymous functions.

Assigning an anonymous function to a variable:

All JavaScript functions can be assigned to variables. More specifically, anonymous functions can also be assigned to a variable.

You can then pass a value or multiple values to the variable that holds the anonymous function. Then, let the anonymous function use the value you pass to the function.

Let us see an example of assigning an anonymous function to a variable.

var abc = function {
    alert('This is an anonymous function');
  }
  abc();

Assigning an anonymous function allows you to call the function at a later time using the defined variable.

The variable is not called immediately, unlike an immediately invoked function expression.

An anonymous function assigned to a variable can take in any number of arguments.

Anonymous functions as an argument to other functions:

Anonymous functions can be used as an argument to other functions. This is the most common method of defining an anonymous function.

The anonymous function that is defined is passed as a function parameter at the same time as it is defined. The anonymous function is defined directly in the input of another function that is being called. The function is defined and then simultaneously passed an input parameter for another function.

Let’s see the below example to understand how anonymous functions can be used as an argument to other functions.

  setinterval (function () {
      alert ('Hello');      
  }, 1000)

The above anonymous function is passed to a set interval. This function will be executed every 1000 milliseconds.

Normal Functions vs. Anonymous Functions

Here is an example of a normal function.

abc();
function abc(); {
    alert('This is a normal function');
}

Let’s now look at the same anonymous function that was described above.

var abc = function {
    alert('This is an anonymous function');
  }
  abc();

In the first example, abc() is written before it is declared. In the second example, it is written after it is declared.

If the function abc() was written before in the first example, the code would not work. The name of the function is used by the function declaration to create a variable.

Anonymous functions cannot be created using these functions because the function must have a name if it is declared before. Instead of the function declaration, the function operator is used to declare anonymous functions.

When to Use an Anonymous Function

It is possible that you have been using anonymous functions all this while without even realizing that the function you used is anonymous.

Anonymous functions can be used if it is an immediately executing function or a call back function. It is also useful inside a for loop or an if statement.

Let us see an example of an anonymous function inside a for loop.

for(var i=0; i<=3; i++) {
    var anonfunction= function() {
    alert("Hi Mr " + x);
    }
    anonfunction();

The syntax of an anonymous function is more concise than that of a standard function declaration.

Anonymous functions are ideal for quick styling DOM elements. They are also preferred for single-line event handlers.

Uses of Anonymous Functions

Anonymous functions can also be used as function closures. Closures are used to provide access to an outer function from an inner function.

Let’s now see how an anonymous function can be used as a closure.

  (function() {
    alert('Hello');
  }());

In the above example, the anonymous function is wrapped in its surrounding parentheses.

A call to the function is initiated by the trailing parentheses which can contain the arguments.

The above example can also be rewritten as follows:


function(message) {
    alert(message);
  }('Hello'));


An anonymous function can use the local variable arguments.callee to call itself. Let’s see an example of this case:

 alert((function(x) {
    return !(x > 1)
      ? 1
      : arguments.callee(x - 1) * x;
  })(20));

Self-Executing Anonymous Functions

An anonymous function that executes by itself as soon as it is created is called a self-executing anonymous function.

A normal anonymous function can be made into a self-executing anonymous function by simply wrapping it in parentheses, adding a set of parentheses and then a semicolon.

Let’s look at another example which shows us how to write a self-executing anonymous function.

 var abc = "This is an example of a variable outside the function.";
(function() {
 var abc = "This is an example of a variable inside the anonymous function.";
 document.write(abc);
})();
document.write(abc);

Advantages and Disadvantages of Anonymous Functions

Let us now see some pros and cons while using anonymous functions as opposed to normal functions.

Debugging: For named functions, the stack trace shows the name of the function and hence it becomes easier to debug normal functions when compared to anonymous functions.

Scope: Anonymous functions are really useful to create a fake block. A function that must be executed immediately does not really need a name.

Brevity: If it is an immediately executing function or a callback function, it is better to keep the function short. Hence, anonymous functions are preferred in these cases.

Recursion: If a function does not have a name and is assigned to a variable, the variable is outside the function’s scope. A function can call itself only when it has a name.

Final Thoughts

Let us now summarize everything that we have covered about anonymous functions.

  • An anonymous function is a function that is declared without a name.

  • An anonymous function can be defined as an immediately invoked function expression, assigned to a variable, or as an argument that is passed to another function.

  • An anonymous function can be used if it is an immediately executing function or a call back function.

  • Anonymous functions are also useful inside a for loop or an if statement.

  • Anonymous functions are used as function closures to provide access to an outer function from an inner function.

  • Anonymous functions are used to call a function that must be executed immediately and does not really need a name.

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:
Written on June 16, 2020