Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Can someone explain the isNaN part of this slide: http://brendaneich.github.io/ModernWeb.tw-2015/#46

I would expect isNaN("LOL") to be true. Why does he put "true?!", and why does Number.isNaN("LOL") evaluate to false?



`isNaN` as it currently exists isn't terribly useful, because anything that can be type-coerced to NaN will return true. If you want to check if something actually is NaN in JS, the common idiom is to test x !== x, since NaN is the only value in JS that is defined as not being equal to itself (don't blame Eich, blame the IEEE floating-point standard). NaN, despite the name, is a "number" that's a result of floating-point calculations with undefined behavior. Sometimes that's a useful thing to test for.

Adding a new, proper isNaN function under a new namespace (Number) lets them do that without breaking the old functionality.


I think I can. The old isNaN() coerces to Number, and non-numeric strings become NaN in JS, e.g. +"LOL" is NaN. However, the new isNaN() just returns false if the value passed isn't of the type Number, which I guess might be useful if you're going to use isNaN() on non-Number values?

Before someone says that NaN means "not a number", technically yes it does, but it is really just a special value of the Number type.

Edit: Oh, zastavka's comment has enlightened me now. I think the reason they changed it is because now it'll check if it's NaN (return true) or anything else (return false), so it'd be like === NaN if you were able to do that. Previously it'd check if it coerces to NaN. I guess the new behaviour is more intuitive.


note that isNaN() will remain as it is today, coercing to a number (and so isNaN('LOL') will continue to return true). Number.isNaN() will have the new behavior, testing for actual IEEE 754 NaN values (and so returning false for Number.isNaN('LOL')). Such is the unfortunate price of backwards compatibility.


probably because NaN has a specific meaning when the value being considered is a number, which "LOL" isn't. If you're calling isNaN, it usually means you're checking explicitly for a number like 1/0, not a string. So really this is a matter of types.

Personally I don't see how this solves much, but then again I'm not a JavaScript guy.


Ironically enough, 1/0 is Infinity, which is a valid number, instead you need to use 0/0 to get NaN. Even worse, the rules for NaN aren't specific to JavaScript, but come from the IEEE 754 floating point standard.

Standard NaN is even weirder: http://en.m.wikipedia.org/wiki/NaN




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: