Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does new Date(undefined) create an invalid date, but new Date(null) does not?

Tags:

javascript

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.

like image 297
lucasvw Avatar asked Jul 30 '18 14:07

lucasvw


People also ask

Why does JavaScript show invalid date?

The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to Date or Date. parse() .

What does new Date () return?

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.

What is new Date () in JavaScript?

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.

How do I know if a date is invalid?

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.


1 Answers

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())
like image 184
Bergi Avatar answered Oct 10 '22 10:10

Bergi