Avatar ·

How to determine if a Date object contains an invalid date in JavaScript?

Hello everyone! I'm a beginner in JavaScript and ran into a problem when working with dates. I need to parse strings that may contain both valid dates (e.g., "2024-10-15") and garbage (e.g., "abc" or "32.13.2024"). I'm using the `new Date()` constructor, but it behaves strangely. Here's an example: ```javascript let date1 = new Date("2024-10-15"); // works let date2 = new Date("abc"); // also creates an object! ``` The problem is that `new Date("abc")` doesn't throw an error, but creates a Date object with an internal value of `NaN`. When I try to output it via `console.log`, I see `Invalid Date`. But how can I programmatically check that the date is invalid? The `typeof` method shows "object", and `instanceof Date` returns `true` even for garbage. I tried comparing with `NaN` — it doesn't work.