What are Immediately invoking anonymous functions in Javascript?

If you had quite experience in any programming language then you probably at least for once have defined a function and you very well know the purpose of using them is that they perform a particular task and can be called repeatedly a multiple number of times.

The general way for defining a function in Javascript is by using function the identifier or simply assign a function to a variable and call them or else you can use fat arrow methods of defining a function which will be explained in detail in this post.

Ways of Defining functions in Javascript

One of the straight forward ways is to define function using function identifier which is followed by name of function and arguments inside brackets.

function show_success_message(){
    console.log("Message sent successfully.");
}
show_success_message();

//Console Output
Message sent successfully.
Declaring and Calling function using Javascript
Declaring and Calling the function using Javascript

The other way is to assign a function to a variable which is similar as assigning values to variables.

var show_success_message = function(){
    console.log("Message sent successfully.");
}
show_success_message();

//Console Output
Message sent successfully.

We can use the fat arrow function which is introduced in the ES-6 version for javascript. ECMAScript (ES in short) which is responsible for standardizing javascript releasing new implementation and features into javascript.

Syntax of Fat-Arrow function

//single line function 
var function_name = (parameter-1, parameter-1, ....) => statement

//Multi-line line function 
var function_name = (parameter-1, parameter-1, ....) => {
    statement
}

Single line function using Fat-Arrow.

var show_success_message = () => console.log("Message sent successfully.");

show_success_message();

//Console Output
Message sent successfully.

Multi-line function using Fat-Arrow.

var show_success_message = () => {
    console.log("Message sent successfully.")
};
show_success_message();

//Console Output
Message sent successfully.

The output of above all functions are the same and only the implementation is different.

Till now we have defined a function that was named and triggered only when called. The functions which have names are called as a named function.

We can also define functions with no name and they will be triggered immediately after defined they are called as immediately invoked anonymous functions or self-invoking anonymous functions.
These anonymous does not have names and are executed automatically. Below is its syntax.

Syntax

(function(){
    //statements
})();

The syntax doesn’t look so different except it doesn’t have a name and identifier function is enclosed inside brackets.
In the end, you can see an empty bracket () followed by a semicolon ;. This empty bracket is similar to calling a function and this executes the inner function inside brackets.

Table of Contents

Some more examples of anonymous functions

let name="foo";
(function(){
    name="bar";
    console.log("The name is : "+name);
})();

//Console Output
The name is : bar

Passing Parameter

(function(first_name, last_name, age){
    console.log("My name is : "+first_name+" "+last_name+" and i'm "+age+" years old.");
})("Jake", "Ron", 25);

//Console Output
My name is : Jake Ron and i'm 25 years old.

anonymous function inside the loop

let arr = [
    {first_name : "Suresh", last_name : "P", age : 21},
    {first_name : "Rahul", last_name : "K", age : 25},
    {first_name : "Kumar", last_name : "L", age : 18},
    {first_name : "Kunal", last_name : "J", age : 20},
];

for(let i in arr){
    (function(first_name, last_name, age){
        console.log("My name is : "+first_name+" "+last_name+" and i'm "+age+" years old.");
    })(arr[i]["first_name"], arr[i]["last_name"], arr[i]["age"]);
}

//Console Output
My name is : Suresh P and i'm 21 years old.
My name is : Rahul K and i'm 25 years old.
My name is : Kumar L and i'm 18 years old.
My name is : Kunal J and i'm 20 years old.
Calling anonymous function within a for loop
Calling anonymous function within a for loop

Why use immediately invoking anonymous functions

  • These functions are invoked immediately after they are defined.
  • These functions are used to executed code only at once.
  • They don’t override or overwrite global data.
  • Unlike normal functions, they don’t remain in scope till the page is refreshed.
  • They avoid global namespace collision
  • Their effect can also be seen in application performance.
  • They can be used to initialization other plugins or modules.

Difference between immediately-Invoked Function, JQuery DOM ready function and Javascript onload, addEventListener event handlers

The immediately-Invoked Function is invoked when a function is defined and program in our case its browser executes as soon as it reads them. This function will be executed before even completing document loading.

JQuery DOM ready function $(document).ready() is an event-handler function that is invoked even document loaded.

$(document).read(function(){
    //statement
});

Javascript event handlers onload and addEventListener are also used to invoke function only after the document is loaded.
The main difference between onload and addEventListener is that onload event handler invokes the named function after the document is loaded. addEventListener is attaching a custom event to the document specifying an action to be taken after the document is loaded.

Below is the example for different event handlers

<body onload="onload_function()" >
    <script>
        // onload event handler
        function onload_function(){
            console.log("1. Function invoked by onload event handler.");
        }

        // Event Listener
        window.addEventListener('load', function(event){
            console.log("2. Function invoked by addEventListener event handler.");
        });

        // JQuery document event handler
        $(document).ready(function(){
            console.log("3. Function invoked by Jquery document ready event handler.");
        });

        // Javascript immediately-Invoked Function
        (function(){
            console.log("4. Function invoked by immediately-Invoked anonymous function.");
        })();
    </script>
</body>

//Console Output
4. Function invoked by immediately-Invoked anonymous function.
1. Function invoked by onload event handler.
2. Function invoked by addEventListener event handler.
3. Function invoked by Jquery document ready event handler.
Javascript example of different on page load event handlers
Javascript example of different on page load event handlers

The Immediately-invoked function is invoked first when compared to other event handlers which are invoked after the document is parsed and loaded.

Conclusion

So it’s time to say bye we have come to the end of our post on What are Immediately invoking anonymous functions in Javascript?. If you have your best way of appending before and after element then do suggest us in the comment section below.

Related Posts

Summary
Review Date
Reviewed Item
What are Immediately invoking anonymous functions in Javascript?
Author Rating
51star1star1star1star1star
Software Name
Javascript Programming
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development