Have you ever wondered why JavaScript returns 'Invalid Date' when setting an (invalid) date? It can be quite confusing and make it difficult to handle errors.
So, what is the optimal way to deal with this issue? One approach is to check the date value after creating a new date object to determine if it is actually a valid date or just a string containing '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
}