A function is a set of statements that take inputs, do some specific computation, and produces output. Basically, a function is a set of statements that performs some tasks or does some computation and then return the result to the user. The anonymous function works the same as the normal function but they differ in terms of syntax.
Let’s consider the following piece of code to understand that how we declare a normal function and an anonymous function:
Now let’s see the following examples (use-cases) that would illustrate more about an anonymous function and its usage.
Example 2: In this example, we will pass a parameter inside our anonymous function that is responsible for taking our result name and further while calling the function, we will provide the name as a parameter value.
Example 3: In this example, we use an anonymous function as a self-invoking function (a special function which is invoked right after it is declared and also it does not have any kind of name associated with it) and this can be done just writing parenthesis in between the function definition.
Difference between Anonymous function & Normal function
A simple function (also called a method) is responsible for carrying out certain operations or tasks. When the function is called, it executes that particular task for which the function has called.
An anonymous function is a function that does not have any name associated with it ie. this was created without any identifier or name that refer to it
We can access this function directly by calling the function.
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.
This function is useful for all scenarios.
An anonymous function can be useful for creating IIFE(Immediately Invoked Function Expression).
An anonymous function can not be hoisted.