![]() |
VOOZH | about |
An anonymous function is a function without a name, mainly used for specific or short-term tasks, and is often assigned to variables or passed as arguments where reuse is not required.
Syntax:
The below-enlightened syntax illustrates the declaration of an anonymous function using the normal declaration:
function () {
// Function Body
}
We may also declare an anonymous function using the arrow function technique which is shown below:
() => {
// Function Body...
}
Note: Parentheses are only required when immediately invoking an anonymous arrow function (IIFE). They are not required for defining a standalone anonymous arrow function.
[Example 1]: An anonymous function is defined to print a message, stored in the greet variable, and executed by calling greet().
[Example 2] : Passing arguments to the anonymous function.
As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function.
[Example 3]: Passing an anonymous function as a callback function to the setTimeout() method. This executes this anonymous function 2000ms later.
Another common use of anonymous functions is to create self-executing functions (also known as IIFE - Immediately Invoked Function Expressions). These functions run immediately after they are defined.
[Example]: Creating a self-executing function.
Arrow Functions are a shorter ES6 syntax for writing anonymous functions, where the function keyword is not required and => is used to define the function.
[Example 1] : This is an example of anonymous function with arrow function.
[Example 2]: A simple arrow function with a single expression is used.
[Example 3]: lllustrates a self-executing function (IIFE), which immediately invokes itself after being defined