I noticed something odd today with Javascript:
console.log(new Date(null)); // 1970-01-01T00:00:00.000Z
console.log(new Date(undefined)); // Invalid Date
Why is this the case? I know null and undefined are not the same, but in this context I would expect the same result.
The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to Date or Date. parse() .
Return value Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date().toString() does.
The new Date() Constructor In JavaScript, date objects are created with new Date() . new Date() returns a date object with the current date and time.
If the variables are of Date object type, we will check whether the getTime() method for the date variable returns a number or not. The getTime() method returns the total number of milliseconds since 1, Jan 1970. If it doesn't return the number, it means the date is not valid.
If new Date
gets called with a single primitive argument that is not a string, it will cast it to a number. And while null
will coerce to 0
, undefined
will become NaN
, and that's the internal value of the date you're getting back.
console.log(null + ":")
console.log(Number(null))
console.log(new Date(null).valueOf())
console.log(new Date(null).toString())
console.log(undefined + ":")
console.log(Number(undefined))
console.log(new Date(undefined).valueOf())
console.log(new Date(undefined).toString())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With