Skip to content

Javascript new Date() not working…sometimes

I can’t figure this out for the life of me. The below code does not give me the day of the week, but instead give me the ‘Choose date’ option:

var year = '21';
var month = '4';
var date = '3';

var dow = new Date(parseInt(year), parseInt(month) - 1, parseInt(date)).getDay() || 'Choose date';

console.log(dow);

If I change the month to ‘3’, it works fine. In fact, it works for the vast majority of combinations I have tried. Another combination that doesn’t work is year = ’21’, month = ’10’, date = ‘2’. What am I missing? I’m trying this in Chrome. Please, help!

Answer

Sunday is considered the first day of the week and therefore if you use getDay() on a date object representing a sunday the output will be 0. The result of 0 || 'Choose date' is 'Choose date'

var date = new Date("2021-01-31T00:00:00.000Z");
console.log(date);
console.log(date.getDay());
console.log(date.getDay() || "Choose Date");

In case you were wondering why the result of 0 || "text" is not 0, it’s because 0 is considered a falsy and the result of falsy || else is always the second part.

You can check this page to see which values are considered falsy (all the values that are not in this group are considered truthy)