JavaScript: Self-Invoking Anonymous Functions

Profile picture for user arilio666

In javascript when you wanna invoke a function without wanting to call it anonymously. There is a special step that can be added to the existing function which will, in turn, invoke the existing function anonymously without calling the respective function.

  • The anonymous function will be invoked after it has been defined with the two () ().
  • The main benefit of this anonymous function is that it will execute the code without declaring any globals.
  • We will lose the reference of the function after it has been declared which means we can use this only once and cannot be used again in the same code.

Syntax

(
    function functionname ()
    {
        //body
    }
) ()

Example: Normal Self-Invoking Anonymous Function

(
    function anime()
    {
        console.log("Naruto Shippuden")
    }
) ()

Output: Naruto Shippuden

This is a normal self-invoking function where it invokes the print statement automatically as we discussed without any function call.

Let us see how we can call this using parameter.

Example: Self-Invoking Anonymous Function Used With Parameters

(
    function selfInvoke(a, b, c)
    {
        console.log(a+b*c)
    }
) (10, 20, 40)

Output: 810

So we can do the normal way of passing parameters to the functions and passing arguments to invoke and pass for in the parameters. But it is advisable not to pass too many arguments since the function becomes larger and later on, we will forget what parameters we used.