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) {
    if(weekends.length > 0) {
      return true;
    } else {
      return false;

migrated from stackoverflow.com Sep 19 '16 at 13:19

This question came from our site for professional and enthusiast programmers.

  • 1
    \$\begingroup\$ Use return weekends.length > 0; instead of that unnecessary if-statement \$\endgroup\$ – Bergi Sep 13 '16 at 15:49
  • \$\begingroup\$ Or return !!weekends.length; \$\endgroup\$ – Dan Korn Sep 13 '16 at 15:50
  • 1
    \$\begingroup\$ Or just return true when you find a weekend: if(iDayOfWeek === 6 || iDayOfWeek === 0) return true;. No need to fill an Array. \$\endgroup\$ – Dan Korn Sep 13 '16 at 15:51
  • \$\begingroup\$ Don't forget that there's a case where you don't return anything, not sure whether this was intentional. \$\endgroup\$ – Bergi Sep 13 '16 at 15:52
  • \$\begingroup\$ 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? \$\endgroup\$ – Dan Korn Sep 13 '16 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();
  • \$\begingroup\$ 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. \$\endgroup\$ – VLAZ Sep 13 '16 at 16:21
  • \$\begingroup\$ 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…). \$\endgroup\$ – RobG Sep 14 '16 at 3:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.