Self Invoking Function (Tutorial – JS)


Self invoking functions are used to stop global scope pollution and ensure the code doesn’t conflict with other code in the page.


(function (a, b) { //Temporary name space for all
// the variables within the function

//code goes here

}() //Invoke the function

); //Without this enclosing parenthesis JS
//will identify this as a function declartion statement only

 

Working example – JSFiddle

var p = 8;
var q = 7;

(function (a, b) {
var x = a * a ;
var y = b * b;
var z = Math.sqrt(x + y);
var r = p + q; // Effects of global scope pollution
console.log(r);
console.log(z);

}(3, 4));

console.log(p); // declaration of variables outside polluted the global scope
console.log(z); // “ReferenceError: z is not defined” = Global scope is not polluted

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s