Aug 14, 2023.
In JavaScript, a day is void if its valueOf()
is NaN
const day = brand-new Day( NaN);.
date.toString();
This is challenging due to the fact that day
still resembles a legitimate day: it is still instanceof Day
, and so on.
One means to look for an “Void Day” is to inspect if the day’s valueOf()
is NaN
:
Number isNaN( date.valueOf());.
const validDate = brand-new Day(' 2022-06-01');.
Number isNaN( validDate.valueOf());
Debugging Why a Day is Void
There are 2 typical factors for an “Void Day”.
The initial is passing a worth that JavaScript can not take a day to the brand-new Day()
contractor as adheres to.
const badDate = brand-new Day(' foobar');.
badDate.valueOf();.
badDate.toString();
Void day strings aren’t the only prospective reason: coming on a numerical computation that amounts to NaN
additionally creates “Void Day”.
const obj = {};.
const badDate2 = brand-new Day( 3 * obj.nonexistentProperty);.
badDate2.valueOf();.
badDate2.toString();
A legitimate day can come to be a void day because of day control techniques like setDate()
and also setHours()
As an example:
const obj = {};.
const badDate3 = brand-new Day(' 2023-06-01');.
badDate3.setHours( 3 * obj.nonexistentProperty);.
badDate3.valueOf();.
badDate3.toString();