Why does JavaScript return 'Invalid Date' when setting an (invalid) date? Seems like it should error out/throw an exception and makes it hard to handle any errors.
Question: What is the best way to handle this to run a check on the date value after you 'new it up' to see if the value is actually a date or a string value of 'Invalid Date'?
const validDate = new Date();
console.log('validDate instanceof Date:', validDate instanceof Date);
const invalidDate = new Date('asdfasdfasdf');
console.log('invalidDate instanceof Date:', invalidDate instanceof Date);
if (invalidDate) {
// This hits because invalidDate is now a string and is therefore truthy
console.log('Date is Valid');
}
if (invalidDate instanceof Date) {
// This hits because it's still an instance of date (although the value is a string)
console.log('Date is Valid');
}
if (typeof invalidDate === 'string') {
// Doesnt hit because invalidDate is not a string
}