Javascript Anonymous Functions

The meaning of the word ‘anonymous’ defines something that is unknown or has no identity. In JavaScript, an anonymous function is that type of function that has no name or we can say which is without any name.

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


Implementation of Anonymous Function

The below code is the implementation of the anonymous function where the function is created for displaying the message as its output.

We have used the function keyword, which is used when we create any function in JavaScript, and the function is assigned to a variable x using ‘let’.

<script>
	let x = function () {  
    	console.log('It is an anonymous function');  
	};  
  x();  
</script>  

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 other function as its argument
  • We can also use an 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:

<script>
	setTimeout(function () {  
    console.log('Execute later after 1 second')  
	}, 1000);
</script>  

The above code implements the use of 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’ see following example to understand how we can do so:-

<script>
	(function() {  
    console.log('Hello!');  
	})();  
</script> 

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 are used for invoking the defined function. In this way, the anonymous function can be invoked immediately.