Why do you need a self-invoking function in JavaScript?

What is a Self-Invoking function?

A self-invoking function is called immediately after definition. For example look at the following codes:

[code lang="javascript"]
(function(){
    // Called as soon as inserted
    console.log("I am running");
})();
[/code]

Why do you need a self-invoking function?

A self-invoking function is an anonymous function and thus all the variables defined inside it are scoped and hence you keep the namespace polution out of it.

[code lang="javascript"]
(function(){
    var i = 0;
    console.log(i); //prints 0
})();
console.log(i); //prints undefined
[/code]

In JavaScript, scopes are “function-level

Why do you need a self-invoking function in JavaScript?

2 thoughts on “Why do you need a self-invoking function in JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top