Excerpts from a wayward programmer.

Wednesday, June 11, 2008 10:52 AM (UTC+05:30)

JavaScript Epic Fail

by D'Jacamo

I'm not much for web browsers as user interfaces for a lot of reasons, but one of the primary causes of my consternation is JavaScript.

Poor JavaScript, the bastard child of Netscape, ECMA, and Microsoft, tied to brittle browser DOMs and saddled with truly weak typing, a clumsy object model, and arbitrarily implemented built in functions. Its name is even misnomer, as JavaScript has nothing to do with Java, being given that name by marketroids to make it sound trendy (imagine, Java trendy!). But despite all this JavaScript excels in many ways, and that's what can make it so infuriating. It can be clever, but more frequently, too clever.

For example, the following code:

var x = '';
var y = 0;
if (x == y)
{
    alert('wtf?');
}

If you run that it's going to put a 'wtf?' on your screen. Why, you may rightfully ask, is '' equal to 0?

Well, it goes like this. In Javascript an empty string and zero are both considered 'false' values, as opposed to a non-empty string and 1, respectively, which are 'true' values. So really you're asking if false == false, and of course that's true. Javascript is doing the right thing, in its own little wacky world of Booleans. For those of us who actually have to program in the language it'd be nice if true was true and false was false and an empty string was an empty string and 0 was just plain zero. I know Javascript is weakly typed, but 0 being equal to an empty string is positively feeble .

I guess I should know better than to compare two different data types and expect something good to come of it, but then, what good is the dynamic typing if not for such occasions?

Turns out the problem is we're not using the right equals. We need to use the 'strict' equality operator of ===, instead of the 'non-strict' version which just can't quite bring itself to impose discipline on those unruly comparisons. The strict equality operator compares both value and type, bringing the unadulterated logical hurt.

So:

if (x === y)
{
    alert('I see dead code...');
}

I think JavaScript didn't go far enough. I think there should be a 'super-strict' equality operator of ====, which compares value, type, and whether I should be using a more sensible language for my browser UI scripting. Unfortunately, in my case, it'd always return true.

Comments (1)

  1. On 9/19/2008, Mike said:

    Thanks for explanation.
    It's really crazy ...

Add a Comment

Name* 
Email
Home Page
Comment*
 
Url for details
Verification*
 
Captcha