JavaScript: The Curious Case of null >= 0
blog.campvanilla.com
JavaScript: The Curious Case of null >= 0
1–10 of 152 posts
Re: JavaScript: The Curious Case of null >= 0
#2Re: JavaScript: The Curious Case of null >= 0
#3Re: JavaScript: The Curious Case of null >= 0
#4Dynamic typing is a nightmare.
Re: JavaScript: The Curious Case of null >= 0
#5Re: JavaScript: The Curious Case of null >= 0
#6Dynamic typing is a nightmare.
Done right (like in python), it's not so bad.
The difference is python is strict about its types and doesn't do automatic coercion. So at least you get type errors at runtime and not magic implicit behaviour.
That said, even Perl did this better (less magic and surprises)... JavaScript is like a language intentionally designed to surprise the developer. Half the time I feel like it's a practical joke that someone accidentally took seriously.
Re: JavaScript: The Curious Case of null >= 0
#7Did he seriously claim at the end that that made sense "mathematically"?
Re: JavaScript: The Curious Case of null >= 0
#8Dynamic typing is a nightmare.
Re: JavaScript: The Curious Case of null >= 0
#9Did he seriously claim at the end that that made sense "mathematically"?
The original error was allowing a nonsense comparison. Which is greater, 10 or fish? If you permit asking this question, you'll occasionally get weird results.
Re: JavaScript: The Curious Case of null >= 0
#10>= and > are numerical operations, so both sides are interpreted as a number, and null is 0 when treated as a number. That means `null > 0` becomes `0 > 0`, which is false, and `null >= 0` becomes `0 >= 0`, which is true. In contrast, == is a much more general operation that works on numbers as well as objects, strings, and all sorts of other things, so it certainly doesn't make sense to always convert both sides to a number first. I'm certainly happy that `null == 0` is false in JavaScript, and I wouldn't want that changed to be consistent with numerical comparison (which comes up much more rarely than equality checks, at least in my code).
This type of issue isn't unique to JavaScript. In Java, if you have boxed Integers, `==` will do object identity comparison (so two different instances of the same number will compare as not equal), while `>=` etc will unbox them and do numerical comparison, which I think stems from the same issue of equality being more general than numerical comparison.
Also worth noting that it's not always true that `a >= b` means `!(a = null` and `'a' < null` are both false.