JavaScript Tutorial

Javascript Anonymous Functions

The meaning of the word 'anonymous' defines something that is unknown or has no identity. In JavaScript, an anonymous function is a type of function that has no name.

When we create an anonymous function, it is declared without any identifier.

Implementation of Anonymous Function

The following code demonstrates the implementation of an anonymous function, which is created to display a message as its output.

In the code, the function keyword is used to define the anonymous function. It is assigned to the variable x using the let keyword. The function can be invoked by calling x().

Use of Anonymous Function

We can use the anonymous function in JavaScript for several purposes. Some of them are given below:-

  • Passing an anonymous function to another function as its argument
    • To pass this anonymous function as an argument for another function.

To understand better, let's implement a code under which we will pass the anonymous function as an argument value for another function:

The above code implements the use of an anonymous function as an argument to a new function where:-

  • Function setTimeout () will output the anonymous function after a second.
  • Created an anonymous function and passed it to the setTimeout () as its argument.
  • Inside it, when the code gets executed, it will print the statement after a second of the execution time.

Immediate execution of a function

In order to invoke and execute a function immediately after its declaration, creating an anonymous function is the best way. Let's see the following example to understand how we can do so:-

In the above code, the anonymous function is invoked immediately where it works as described in the following way:-

The first step is to define the function expression. After defining the function, we can see the trailing parenthesis () followed by the terminator ";" that is used for invoking the defined function. In this way, the anonymous function can be invoked immediately.

Go back to Previous Course