auto invoke function javascript syntax

Auto Invoke Function JavaScript Syntax

JavaScript has a unique feature of allowing functions to invoke automatically, without being explicitly called. This feature is called "Auto Invoke Function" or "Immediately Invoked Function Expression (IIFE)". It is a self-invoking function that can be executed as soon as it is defined. The syntax for auto-invoking function in JavaScript is as follows:

 
(function(){
    // code goes here
})();

This type of function is often used to create a private scope for variables and functions so that they do not interfere with other code on the page. It can also be used to create modular code that is easy to manage.

Example:

Let's say we want to create a counter that increments every time a button is clicked. We can use an auto-invoking function to maintain the state of the counter:


<div id="counter"></div>

<script>
(function(){
    var count = 0;
    
    function increment(){
        count++;
        document.getElementById("counter").innerHTML = count;
    }
    
    document.getElementById("btn").addEventListener("click", increment);
})();
</script>

In this example, we have created an auto-invoking function that creates a private variable "count" and a function "increment" that increases the value of "count" by 1 every time it is called. The function also updates the text of the "counter" div element with the current value of "count". Finally, we have added an event listener to the button with id "btn" that calls the "increment" function whenever it is clicked.

We have wrapped all of this code inside an auto-invoking function so that the "count" variable and "increment" function are not accessible outside of the function, thus preventing any conflicts with other code on the page.

There are other ways to achieve the same thing, such as using ES6 modules and classes, but auto-invoking functions are still widely used due to their simplicity and flexibility.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe