The dynamic nature of JavaScript makes it fascinating. The fact that function can be created as well as modified at runtime is one of the amazing stuff you can do in JavaScript unlike in static languages like Java and C#.

Consider an example of function rewriting at runtime below:

function temp() {

alert('first time only');

temp = function () {

       alert('rest of the time');

}

}

temp();

temp();

temp();

temp();

The first call to temp() will generate a pop up with message ‘first time only’ and all subsequent will generate pop up with message ‘rest of the time’.

Function rewriting can be used intelligently to boost performance of your JavaScript code. Often in your code you have one off statements to execute or conditions that evaluate to same value every time.

Like the one below which returns an DOM object using document.all if it is IE else document.getElementById()

function GetDOMObject(id) {

if (isIE()) {

        return document.all[id]

}

else {

       return document.getElementById(id);

}

}

The function isIE() returns true if the browser is IE else returns false.

Now as browser features don’t change as you interact with a web page, the ‘if.. else’ condition seems an overhead whenever call to GetDOMObject is made. With some smart rewriting the function can be modified to:

function GetDOMObject(id) {

if (isIE()) {

         GetDOMObject = function (id) { return document.all[id]; }

         return document.all[id];

}

else {

        GetDOMObject = function (id) { return document.getElementById(id); }

        return document.getElementById(id);

}

}

When the method is access for the first time, the isIE() method is called to determine the type of the browser. Depending on the value return, the function GetDOMObject is rewritten to eliminate the if .. else conditions. So if the browser is IE, the function GetDOMObject() is modified to : function GetDOMObject(id) { return document.all[id]; }

The function GetDOMObject() can further be modified to reduce a line or two:

function GetDOMObject(id) {

if (isIE()) {

      return  (GetDOMObject = function (id) { return document.all[id]; } )()        

}

else {

      return ( GetDOMObject = function (id) { return document.getElementById(id); } )();

}

}

The trailing parenthesis to the assignment statement execute the modified GetDOMObject() function there itself.

However, though function rewriting is a smart way to speed up your JavaScript code, the performance improvement may not be significant unless your website is JavaScript intensive.