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;The above code is not optimized. In Javascript, we can utilitize 'autocast' feature that will reduce the code into:
...
if (str != null && str != '') { }
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
2 comments:
great job !
Given this is one of the first results in a google search for javascript autocast I thought I should add that you can also define values using autocast to create a default for missing values in functions.
function(someString){
var myString = someString || "";
}
This will define myString to an empty string even if it isn't defined.
Post a Comment