# Function to search for weekends left in month

I have a function that returns true or false depending upon whether there are any weekend days left in the month. Is there a better/cleaner way that I can write this?

function checkWeekendsLeft(month, year) {
var iDaysInMonth   = new Date(year, month, 0).getDate();
var iCurDayInMonth = new Date().getDate();
var x              = new Date();
var weekends       = [];

if (iDaysInMonth >= iCurDayInMonth) {
for(var i = iDaysInMonth; i >= iCurDayInMonth; i--) {
var iDayofMonth = i;
var date = new Date(year, month - 1, iDayofMonth);
var iDayOfWeek = date.getDay();
if(iDayOfWeek === 6 || iDayOfWeek === 0) {
weekends.push(iDayOfWeek);
}
}
if(weekends.length > 0) {
return true;
} else {
return false;
}
}
}

• Use return weekends.length > 0; instead of that unnecessary if-statement Sep 13, 2016 at 15:49
• Or return !!weekends.length;
– Dan Korn
Sep 13, 2016 at 15:50
• Or just return true when you find a weekend: if(iDayOfWeek === 6 || iDayOfWeek === 0) return true;. No need to fill an Array.
– Dan Korn
Sep 13, 2016 at 15:51
• Don't forget that there's a case where you don't return anything, not sure whether this was intentional. Sep 13, 2016 at 15:52
• Also, I would think you would either pass a full date to the function, or pass no date at all and use the current date. Do you really need to know whether some arbitrary month in some arbitrary year has weekends left based on the day of the current month?
– Dan Korn
Sep 13, 2016 at 15:54

You could use something like this :

function hasWeekendDaysLeft() {
var today = new Date();
var lastDayInMonth = new Date(today.getYear(), today.getMonth() + 1, 0).getDate();
var numToday = today.getDate();

return lastDayInMonth - numToday > 6 - today.getDay();
}

• I think this is a good solution. Although depending on the exact requirements, it might be off by 1 - if you check hasWeekendDaysLeft for the last Sunday of the month it reports false. Whether that's valid or not will depend if you consider the current day "upcoming" or not. Which is a very widely encountered problem with dates, so, it's not an issue as much as in need of clarification. Other than that, it's not bad.
– VLAZ
Sep 13, 2016 at 16:21
• This could be optimised a little to first test !(numToday%6) || ... so that if today is Saturday or Sunday it immediately returns true (presuming that's the required logic of course…).
– RobG
Sep 14, 2016 at 3:19