When to use anonymous JavaScript functions?


The code while using anonymous functions is more readable when handlers are to be defined inside the calling code. Anonymous functions are declared inline. Normally, inline functions are better since they can access variables in the parent scopes.

It allows for creating a function without any names identifier. It can be used as an argument to other functions. You can call them using a variable name.

This is how JavaScript anonymous functions can be used −

var func = function() {
   alert(‘This is anonymous');
}
func();

Here’s an example −

//anonymous function
var a = function() {
   return 5;
}

Updated on: 23-Jun-2020

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements