Wednesday, October 29, 2014

Code optimizations and new standards

Most of the times the use of some new standards of JavasScript, known as ECMAScript, is constraint by browser compatibility. The latest browsers along with IE from version 9 implement many or all of these new features. See ECMAScript 5 compatibility table.

This post is also about code optimization. One of the most important point to have in mind at coding in JavaScript is to avoid unnecessary repetitions to accelerate execution and save bytes of code.

Lets see some examples of these concepts. These functions do the same in different ways:

Not optimized code:
var retval = false;
if ((window.location.href.toLowerCase().indexOf('/candidate1/list.aspx') > -1) ||
    (window.location.href.toLowerCase().indexOf('/defaultcompany.aspx') > -1) ||
    (window.location.href.toLowerCase().indexOf('/defaultcompanyv2.aspx') > -1)) {
 retval = true;
}
return retval;

Optimized code with JavaScript:
var retval = false,
    _href = window.location.href.toLowerCase(), 
    _a = ['/candidate1/list.aspx','/defaultcompany.aspx','/defaultcompanyv2.aspx'];
for (var i = 0; !retval && i < _a.length; i++) retval = (-1 != _href.indexOf(_a[i]));
return retval;

Optimized code with jQuery:
var _href = window.location.href.toLowerCase();
return $.map(['/candidate1/list.aspx','/defaultcompany.aspx','/defaultcompanyv2.aspx'],function (e) { return _href.indexOf(e) != -1 ? 1 : null; }).length;

Optimized code with JavaScript (ECMAScript 5):
var _href = window.location.href.toLowerCase(), 
return ['/candidate1/list.aspx', '/defaultcompany.aspx', '/defaultcompanyv2.aspx'].some(function (e) {
  return -1 != _href.indexOf(e);
});