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.

Shiv Kumar Ganesh
1 min readAug 7, 2017

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.

--

--

Shiv Kumar Ganesh
Shiv Kumar Ganesh

Written by Shiv Kumar Ganesh

Interested in friends and am a Web Developer. Design Websites and Web Solutions in major Platforms, SEO Consultant

No responses yet