whatspop - Kunal Anand

JavaScript nulls

4/09/2007

I got burned by JavaScript today. Here is some code - note, I've reduced the code to the pedagogical issue:

function RunTest(a, b)
{
test = null;

if (a == b) {
test = "They are the same.";
}

return escape(test);
}

Provided the comparison fails, the returned value should be null. Yet in a failing case, JavaScript returns a string with the value of "null" - weird. I expected an exception, or even an empty string to be returned. As a tangent, you know you've spent a lot of time in a strongly typed language when you start complaining about throwing exceptions for functions that deal with nulls.

In this case, if you have conditional logic that invokes the RunTest function, then testing for a null value (failing case) is useless. Fundamentally, you will never want to structure your workflow around nulls, but in case you do - just be careful.

About I am currently a Senior Engineer at MySpace. Feel free to check out my personal collective.

Archives
April 2005
May 2005
June 2005
July 2005
August 2005
September 2005
October 2005
November 2005
December 2005
January 2006
March 2006
April 2006
May 2006
June 2006
July 2006
August 2006
September 2006
October 2006
November 2006
January 2007
February 2007
April 2007
November 2007
December 2007
January 2008
March 2008
April 2008
May 2008
June 2008

Subscribe to my feed