Hi I'm looking for a good explanation for this simple code
why isNaN(new Date(some date))
gives false
? (typeof return object)
This is an object and as far as i know isNaN function explicitly converts to a number, so if I pass different object to isNaN it returns true.
The first thing that isNaN()
does is convert its parameter to a number (as you yourself wrote). If the parameter is an object, that's done by calling the .valueOf()
method of the object. In the case of Date instances that returns the timestamp, and it won't be NaN
for any valid Date.
Try this:
alert(isNaN({ valueOf: function() { return 12; } }));
And for an invalid date:
alert(isNaN(new Date("potatoes")));
That'll be true
. If you want a stricter isNaN
you can use Number.isNaN
:
alert(Number.isNaN(NaN)); // true
The version of isNaN
on the Number constructor won't coerce its argument to a number; it's job is to say whether the thing you pass in is the NaN
value, without any type casting. So by that function, there's one and only one NaN
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With