Anonymous function
is a function that does not have any name associated with it.
Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions, we use only the function keyword without the function name.
The following shows how to define an anonymous function:
(function() {
//function body
});
Note that if you don’t place the anonymous function inside the ()
, you’ll get a syntax error. The ()
makes the anonymous function an expression that returns a function object.
We may also declare an anonymous function using the arrow function technique which is shown below:
( () => {
// Function Body...
} );
Understand the Anonymous function with the example:
An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value.
For example, the following shows an anonymous function that displays a message:
let greetMessage = function(){
console.log("Welcome User!");
}
greetMessage();
//Output: Welcome User!
In this example, we need to call the anonymous function later, we assign the anonymous function to the greetMessage
variable. We can call the function by invoking greetMessage()
.
Since the whole assignment of the anonymous function to the show variable makes a valid expression, you don’t need to wrap the anonymous function inside the parentheses ()
.
Passing arguments to Anonymous function:
In the next example, we pass arguments to the anonymous function.
let greetMessage = function(userName) {
console.log("Welcome",userName,"!");
}
greetMessage("Sudipta");
//Output: Welcome Sudipta !
We can write it as an arrow function as below.
let greetMessage = (userName) => console.log("Welcome",userName,"!");
greetMessage("Sudipta");
//Output: Welcome Sudipta !
Using the Anonymous function as a parameter:
we can also pass anonymous functions as parameters into another function.
setTimeout(function(){
console.log("Executes after 10 seconds.");
}, 10000);
//Output: Executes after 10 seconds.
In this example, we pass an anonymous function as a callback function to the setTimeout()
method. This executes this anonymous function 10000ms later.
Invoking the Anonymous function immediately:
Another use case of anonymous functions is to invoke the function immediately after initialization, this is also known as Self Executing function. This can be done by adding parenthesis so we can immediately execute the anonymous function.
(function() {
console.log("Hello!");
}) ();
//Output: Hello!
In the above example, at first, we define a function expression and return a function. Then we call the function by adding the trailing parentheses ()
.
Conclusion:
Anonymous functions are functions without names.
Anonymous functions can be used as a parameter to other functions or as an immediately invoked function execution.
Thanks for reading 😊... Hope it will help you to understand Anonymous function.