How to Immediately Invoke a function — Self Invocation

Self Invocation of a function is a way in which you can protect your Global Scope by not exposing the variable to the Global Scope. This helps to prevent your code and protect it from accessing the Global Environment.

The way in which you can enable Self Invocation is as follows.

(function() {
// Your Code Goes Here!!
})();

Self Invocation with Arguments

Its possible to pass Arguments to the above code in order to protect the global scope as well as invoke it automatically. You don’t need to invoke this piece of code since it can automatically invoke itself. Now let’s see how we can have a variable being passed to this function.

(function(_) {
// _ represents the underscore library. This can be any variable as such;
})(_);

Check out all the other posts on JavaScript Essentials to get a Grasp of these JavaScript Utilities.


Originally published at The Web Juice.

Show your support

Clapping shows how much you appreciated Shiv Kumar Ganesh’s story.