Live data from Hacker News

Javascript null surprise

news.ycombinator.com

1–10 of 25 posts

Javascript null surprise

#1
I just encountered this while tracking down a bug in some Javascript (verified in FF and IE):

   null  false
but

   null  true
Would you expect that? I didn't. Obviously . Time to look up all uses of = in my code...

p.s. Is this too trivial to post here? Too specialized? I'm curious.

Re: Javascript null surprise

#3
Interesting and not what I would have expected. I just confirmed it in Opera. Also, nullYou can use the following javascript link to confirm this:

(Note - I can't ever remember how to embed links properly in YC... is there a reference somewhere?)

javascript:alert('null 0: '+(null>0)+'\nnull null: '+(null>null)+'\nnull<=null: ' + (null<=null));

Re: Javascript null surprise

#5
post #3

Interesting and not what I would have expected. I just confirmed it in Opera. Also, null You can use the following javascript link to confirm this: (Note - I can't ever remember how to embed links properly in YC... is there a reference somewhere?) javascript:alert('null 0: '+(null>0)+'\nnull null: '+(null>null)+'\nnull<=null: ' + (null<=null));

In Safari 3 and Firefox 1.5, at least, null == null, so I would expect null Both Safari 3 and Firefox 1.5 do the decidedly unexpected null <= 0 thing.

Re: Javascript null surprise

#7
post #6

Okay... I have another one. In Python: >>> -1 % 3 2 In Javascript: >>> -1 % 3 -1

That is actually an error in the python implementation. According to the language reference: "(a/b)*b + (a%b) = a" where the (a/b) step is rounded towards 0. This implies the if a is negative, (a%b) should also be negative. Note that this modulus standard is also used for the C, C++, and JAVA standard. Here, its python's mess up.

Re: Javascript null surprise

#9
[Rhino book] > When null is used in a Boolean context, it converts to false. When used in a numeric context, it converts to 0. And when used in a string context, it converts to "null".

Re: Javascript null surprise

#10
post #9

[Rhino book] > When null is used in a Boolean context, it converts to false. When used in a numeric context, it converts to 0. And when used in a string context, it converts to "null".

So I guess the confusing bit is that null==0 is Boolean, rather than numeric, context.
Post reply on HN