JS Performance: 10 Commandments

  1. Don’t touch the DOM
  2. Cache DOM reference in local vars
  3. Use selectors API
  4. Cahce the length when looping collections
  5. Update the DOM offline
  6. Batch style changes
  7. Don’t ask for layout info excessively
  8. Minimize reflow areas
  9. Use event delegation
  10. Don’t touch the DOM

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

}(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