Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Anonymous Function?
2.1.
Defining Anonymous Function
2.2.
Calling Anonymous Function
3.
Applications of Anonymous Function
3.1.
Immediately Invoked Function Execution(IIFE)
3.2.
Anonymous Functions as the argument to other functions
4.
Drawbacks of Anonymous Functions 
5.
Frequently Asked Questions
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Anonymous Functions in JavaScript

Author Vidhi Singh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Like, every other computer language, Javascript also supports functions. Usually, while defining a function, we specify a name, sometimes parameters, and then whatever we want the function to do in form of expressions. But, anonymous functions do not follow these norms of usual functions. Like the word “Anonymous”, which means “whose name is not known”, thus, anonymous functions do not have a name. 

Let’s discuss anonymous functions in detail. 

Also Read About, Javascript hasOwnProperty

What is Anonymous Function?

As mentioned earlier, in JavaScript, Anonymous Functions are functions that are not given any name or identity. In other words, they are not assigned with identifiers. The different type of function with a name is said to be “Named Function”. They are normal functions similar to functions in most other languages. 

In JavaScript, Anonymous functions are created at run time.  

Defining Anonymous Function

To define the anonymous function, we simply use the function keyword (similar to how functions are defined in other languages) and then brackets (). We may or may not have parameters according to the need of the function. Then, we write the function's body, enabling the function to do a specific task.

Syntax:

(function (parameters)
{
	//body of the function
});

 

Here, it is important to put the function in a bracket() followed by a semi-colon. Normally, when we define a function, we don’t use a semicolon, but for anonymous functions, it is mandatory to use a semicolon because it returns an object. Otherwise, it generates a run time error. 

For example:

<script>
	function ()
	{
		console.log("Coding Ninjas");
	}
</script>

 

Output:

This is because it is treated as an object.

The correct way will be as follows:

<script>
	(function ()
	{
		console.log("coding Ninjas");
	});
</script>

 

Output:

As anonymous functions do not have a name, they can not be called from anywhere in the program. In the above code as well, the function is just defined. You may wonder if they can ever be called. 

So you see the anonymous functions do not have a name. Therefore, they cannot be called anywhere, unlike the named functions. But in the cases you intend to use them more than once, there is a way to achieve it. The object returned by the anonymous function can be stored in a variable. 

Something like this:

<script>
	var one=(function ()
	{
		console.log("Coding Ninjas");
	}); 
</script>

 

Here, the object returned by the anonymous function is stored in variable ‘one’. 

It can also be done using the arrow function like this:

<script>
	var one=()=>console.log("Coding Ninjas"); 
</script>

Calling Anonymous Function

Anonymous functions are self-invoking or self-executing. This means they are called just after the declaration. They are called using brackets() just after declaring the function. 

The syntax for the same will be:

(function(parameters)
{
	//body of the function
})();      //the brackets here are invoking it 

 

For example:

<script>
	(function ()
	{
		console.log("Coding Ninjas");
	})();
</script>

 

Output:

Coding Ninjas


If we do not use the invoking brackets after function definition, they will be just defined and not called. That will not produce any kind of error, as demonstrated before in this article.
But, using this, they can be invoked only once. To access them in other parts of the program as well, we use the variable that stores them. 

Something like this: 

<script>
	var one=(function ()
	{
		console.log("Coding Ninjas");
	});   
	one();
</script>

 

Output:

Coding Ninjas

 

Here, let’s make a small difference and see the result

<script>
	one();
	var one=(function ()
	{
		console.log("Coding Ninjas");
	});    
</script>

 

Output:

 

We definitely did not expect this. The reason is the hoisting concept of JavaScript. But, here the catch is that the anonymous functions do not get hoisted. 

Hoistingin brief, implies that in the creation phase of the execution process, function declarations are shifted to the top of the code. 

To read more about Hoisting in JavaScript, you can also refer to this article

Since they do not get hoisted, they are created in run time. This further implies that they are created only after they are declared. Therefore, they can only be used after declaration. Calling or trying to use an anonymous function before its declaration line generates an error. 
Therefore, this is an exception and should be kept in mind while using them.  

The arrow function can be executed in a similar fashion.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Applications of Anonymous Function

Let us discuss some common use cases and applications of anonymous functions in javascript.

Immediately Invoked Function Execution(IIFE)

Since anonymous functions can only be called as and when declared without any hassle, they are preferred in situations where the functions need to be executed as soon as it is declared. 
Talking about Immediately Invoked Function Expression, it is a JavaScript function that runs as soon as it is defined

Let’s make this clear using an example:

<script>
	for (var i=1;i<=3;i++)
	{
    	(function(counter) 
    	{
        	setTimeout(function() 
        	{
            	console.log(`Counted till ${counter} after ${counter} seconds`);
        	},1000*i);
    	})(i);
	}
</script>

 

Output:

Counted till 1 after 1 seconds
Counted till 2 after 2 seconds
Counted till 3 after 3 seconds


Inside our code, we use the setTimeout(). We maintain a timer, using variable ‘i’, which waits for 1000*i milliseconds(1 second)  before executing the code. After that, the function logs the message, with the counter value and number of seconds after every second. 

The above example also uses the concept of synchronous and asynchronous behaviour of JavaScript.

Anonymous Functions as the argument to other functions


Performing tasks for event handlers, listeners, callbacks involves extensive use of this concept. 
Let’s see callbacks in detail using the concept of anonymous functions and IIFE.
When we execute the function as soon as declaring it, like this,

 

 

Taking an example,

<script> 
	var val=[0,1,2,3]
	console.log(val.map(function(x){return x+1}));      //anonymous function has been used 
</script>

 

Output:

1,2,3,4 

You can practice by yourself on an online javascript compiler.

 

Without the use of the anonymous function, it will look something like this:

<script>
	var val=[0,1,2,3] 
	function increment(x)
	{
		return x+1;
	}
	console.log(val.map(increment));      //named function has been used 
</script>

 

Although both give the same result and are correct, it is the way the earlier function has been implemented that makes it more compact and readable. It also makes writing code for the developer hassle-free. 

Also, since the defined function does not seem to be of use in other places, it is wise to make it an anonymous function. Do not worry about map() function. In short, the map() function generates a new array containing the results of calling a given function on each element in the calling array.

We hope now you know how anonymous functions can be used as arguments for other functions.

Drawbacks of Anonymous Functions 

A few disadvantages of anonymous functions are:

  • Reusability is an issue of anonymous functions
  • Debugging becomes very difficult in large programs with a high number of lines of code. This is because in the call stack also, there is no name of the anonymous function.

 

There are other drawbacks as well, but they occur according to the situation. 

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

  1. What are anonymous functions in JavaScript?
    Anonymous functions are functions that have no identifier associated with them.
     
  2.  Are anonymous supported in any other language other than JavaScript?
    Few other languages that support anonymous functions are C#, Scala, Golang, etc.
     
  3. Do anonymous functions have a name in the call stack?
    No, in the call stack also, they are stored as anonymous only. 

Conclusion

This article extensively discusses the anonymous functions in JavaScript. We also explain its properties in detail. 

We hope that this blog has helped you enhance your knowledge regarding Anonymous Functions in JavaScript, and if you would like to learn more, check out our articles on JavaScript. Do upvote our blog to help other ninjas grow. 

Happy Coding!    

Previous article
IIFE in JS
Next article
Higher-Order Functions in JS
Live masterclass