What is an anonymous function in JavaScript?


Like other advanced languages, JavaScript also supports anonymous functions. From the word anonymous, it is clear that when a function has no identifier or no name, that function is called an anonymous function. The only difference between anonymous function and normal function is that normal function has names but anonymous functions do not have any Additionally, anonymous functions are used for simpler and shorter applications which are easier to maintain. In this article, we shall cover what is an anonymous function in JavaScript, how we can use them, their syntax and basic usage as well as advantages and limitations.

Syntax

const EnumType = {
   variable = function () {
   function body
};
// to call the function variable()

In the above syntax, we can see that the function keyword is being used but there is no name. The final function is returned to a variable. This variable can be used as the function. Moreover, we can also assign the same to some other variable which then can be used as a function. Let us see one example for better understanding.

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { function normalFunction() { content += "Output from a normal function." + '<br>' } var f = function () { content += "Output from an anonymous function." + '<br>' }; f() normalFunction(); // assign f to some new variable f1 = f f1() } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

Now the question comes, if we do the same thing with normal functions and the anonymous functions, then why should we use the anonymous function? Or why do we use normal functions instead of anonymous functions? The answers are given in the following subsections −

Passing function as an argument

Sometimes we pass a function (not the result after the function call) as another function parameter. Let us see one example where we print a line after waiting for 2 seconds (2000 milliseconds)

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { setTimeout( function () { content += "Output is coming after 2 seconds (2000 milliseconds)" + '<br>' opDiv.innerHTML = content }, 2000 ); } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

In this example, we are using the setTimeout() function which takes another function as an argument and another value to wait for sometimes and after that executes the given function. Here we have used 2000 so that it will wait 2 seconds and then execute the anonymous function.

Immediate execution of functions

In some cases, we define the function and immediately execute them. In such a scenario anonymous functions become handy. Such syntax is given below−

Syntax

(
   function (){
      //function body
   }
)();

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { ( function () { content += "Execute immediately after declare this function" + '<br>' } )(); } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

Advantages and Disadvantages of Anonymous Functions

Anonymous functions are helpful sometimes as it is declared inline. These functions have full access to all current local variables so that it simplifies the code and its design. And this does not interfere with any namespace we are using (global, local, inside a function, etc.) This is only because the anonymous functions have no name.

In some cases, anonymous functions are not suited well. For example addEventListener(type, function) in this event handler, which we cannot remove because we do not have a handle on this function. Another disadvantage is that whenever we use an anonymous function, it will create a new instance of it. And in some cases, we can use normal functions as well. Using an anonymous function does not make any difference in that scenario. We may not see any difference in such cases but consider we are using a function inside one loop, and each time we are creating one inside this loop. In such cases, it will be a major performance issue if the anonymous functions are used.

Conclusion

Javascript functions are themselves smart. We can pass functions as parameters of some other functions. But sometimes we need to apply certain operations on each element of an array or similar such cases we can define our goal as an anonymous function for which, it does not need any special reason to create a new standard function. Anonymous functions can also take parameters. For javascript promises, we can handle errors or promise resolve by using anonymous functions as well.

Updated on: 23-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements