5

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.

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
kuba0506
  • 455
  • 2
  • 8
  • 20
  • Well, what does `+new Date()` give you? Not not a number (for valid dates) – Ja͢ck Sep 06 '14 at 16:50
  • 1
    That actually depends on `some date`. If it is invalid, your expression would give `true`. – Bergi Sep 06 '14 at 16:50
  • See also [this question](http://stackoverflow.com/q/1353684/1338292) and [this one](http://stackoverflow.com/questions/3340055/how-to-check-if-new-datesome-date-was-able-to-parse-correctly). – Ja͢ck Sep 06 '14 at 16:53

2 Answers2

15

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    This is not true anymore. The line `alert(Number.isNaN(new Date()));` now also returns false (see https://jsfiddle.net/wkrhut9f/) – NoRyb Apr 08 '19 at 06:56
  • @NoRyb that's interesting, thanks — I think I just whipped out a bad example here. – Pointy Apr 08 '19 at 12:23
1

Checking with isNaN tries to convert its parameter to number and if this is not a number then only it gives you the result true. But if the date passed as the parameter it shows you the false as it is converted to number.

Whatever you pass in the parameter if that returns number successfully then it give you the result to be false else it gives you the true.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231