Skip to content
the poor coder

auto invoke function javascript syntax

Poor Man
Published
Reading time
1 min read

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:

Text
 
(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:

Text

<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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC