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