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

Worth Sharing?

2 Comments

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>