Tuesday, September 05, 2006

Javascript Autocast

A typical day at work requires me to constantly switch between writing code in C# and Javascript. This effects the way I write code in both languages. Since C# is more strict that Javascript, my coding style leans towards C# and sometimes I find myself writing Javascript code in C# style, which can be viewed as good or a bad thing.

Every language has its goodies that if we take advantage of can produce better quality code.

Let's take a common task as example. We want to test a string variable for null and empty.

In C#,I will do like:


string str;
...

if (str != null && !str.Equals(string.Empty)) { }


Applying the same C# style to Javascript will result in the following code:

var str;
...
if (str != null && str != '') { }

The above code is not optimized. In Javascript, we can utilitize 'autocast' feature that will reduce the code into:

var str;
...
if (str) { }

A null or an empty string autocasts into false, and therefore the condition is evaluated as false.

As you can see, the code is much shorter and cleaner. Size does matter in Javascript. Shorter code translates into faster download time.

Autocast also applies to other types/conditions:

  • Undefined variable is evaluated as false. A variable is undefined if it hasn't been assigned a value.
    Example:

    var myVar;
    if (myVar) { } // false


  • Empty string is evaluated as false

    var myStr = '';
    if (myStr) { } // false

    var myStr2 = 'ABC';
    if (myStr2) { } // true

  • Zero is evaluated as false

    var myNum = 0;
    if (myNum) { } // false

    var myNum2 = 1;
    if (myNum2) { } // true

  • Null is evaluated as false

    var myObj = null;
    if (myObj) { } // false

  • Object is evaluated as true

    var myObj = {};
    var myObj2 = new Object();
    if (myObj) { } // true
    if (myObj2) { } // also true


  • Empty array is evaluated as true
    An array is essentially an object, therefore it is evaluated as true.

    var myArray = [];
    var myArray2 = new Array();
    if (myArray) { } // true
    if (myArray2) { } // true

Friday, September 01, 2006

Javascript optimization

The Internet Explorer Team (the team that brings us IE 7) has posted a nice article about Javascript optimization. This is the first part of the scheduled 3 parts article. In this article, the main drive behind the optimization is to reduce the number of symbolic lookups made by the Javascript engine to map the variable name to its real object.

It is quite rare to find such optimization tips from the maker of the browser. I am glad finally IE team pays some attention to improve the Javascript development. We need more articles like this, as more and more Javascript code is written nowdays. In my current project which is using ASP.NET 1.1, about 75% of the UI code is written in Javascript, and the rest is the C# code behind.

Please find the article here