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.