Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript why isNaN(new Date()) is false

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.

like image 749
kuba0506 Avatar asked Sep 06 '14 16:09

kuba0506


1 Answers

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.

like image 129
Pointy Avatar answered Oct 06 '22 00:10

Pointy