JavaScript's 'Invalid Date' Is an Object, Not a String — A Common Validation Pitfall
A developer building a Unix timestamp converter discovered a subtle but widespread JavaScript bug while adding input validation to the tool. When an invalid date string is passed to the Date constructor, JavaScript returns a Date object with an internal NaN value rather than throwing an error or returning the string 'Invalid Date'. This means a strict equality check like `new Date(garbage) === 'Invalid Date'` always evaluates to false, rendering the guard clause completely ineffective. In the converter, the tool still appeared to work correctly, but only because JavaScript's falsy treatment of NaN happened to blank the output field as a coincidental side effect. The reliable fix is to use `isNaN(new Date(input).getTime())` to properly detect invalid date input.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in