Self-Invoking Function in JavaScript

Self-Invoking Function in JavaScript

·

1 min read

A self-invoking function is used to avoid any name scope collision of variables and functions, especially when you have a huge code in your file and you also need to add a third-party library. Because there is a high chance of repeating names of variables and functions. Using these functions helps solve this problem and names can be used again and again. Also, this way there is very little clutter in the code and it's easily understandable. You also do not need to call this function in order to make your code work, it runs automatically.

Here's an example,

(function(){
    for(let i = 0;i< 5;i++){
        console.log(i)
    }
}())
0
1
2
3
4

This function automatically prints 0-4. You don't have to call it. It will run automatically.

Buy me a cup of coffee