Photo from Flickr: tiswango/54740642 Photo by tiswango @ flickr

Javascript compare

published on
May 18th, 2006
by Marko Mrdjenovic

Today I found something in Javascript that just doesn’t make any sense. Ok, maybe some other things don’t make sense either, but I think this one just beats all of them.

Let’s say we have a string and a number:

a = "1";
b = 1;

Now we want to compare these:

alert((a>b) ' : ' (aa) ' : ' (b==a));

Both will give you ‘false : false : true’.

If we change a to “2″

a = "2";
b = 1;

we get a ‘true : false : false’. We’re still OK.

Now let’s change a to “a”

a = "a";
b = 1;

The weird thing is we get ‘false : false : false’ on both alerts.

In typestrict languages you’d get an error. Or at least you should. In php you get a ‘false : true : false’ and ‘true : false : false’ which would mean they decided that all strings are smaller than numbers. This is weird – if you make b a string “1″ the return values change – but at least they made a choice.

For what I can comprehend Javascript casts both values to int and I can understand that. The core of the problem is obviously with the NaN value. What I can’t understand is how something’s not smaller, not bigger and not equal at the same time? I’m sure someone can explain this…

Opinions

  1. posted on
    May 19th, 2006
    by Marko

    Is a dream bigger than an apple?

    That’s how :)

  2. posted on
    May 19th, 2006
    by Marko Mrdjenovic

    I could accept that in typestrict languages. And I would even accept it here, but how come then

    var a = ['a',1];
    alert(a.sort().join());
    var b = [1,'a'];
    alert(b.sort().join());

    both return ’1, a’. Doesn’t this mean that it decides that 1 is smaller than ‘a’ ?

  3. posted on
    May 19th, 2006
    by Marko

    I don’t know, it might. But my point is that if you go comparing uncomparable items, then you can reasonable expect undetermined result.

Express your opinion

My name is Marko Mrdjenovič and I’m a web developer and a manager from Ljubljana, Slovenia (N 46° 03.246,W 14° 30.265).

I like solving problems. I do that by writing code, managing projects and people. I like creating good experiences. And going to conferences. I work at Zemanta. I do freelance UX/front-end/back-end work, available from March.

Blog archive

Advertisments

Jobs

Come in, we're hiring

Full-time and freelance job opportunities available at Authentic Jobs:

  • Loading ...

Post a job and reach web professionals everywhere.