0

This snippet should print the number of days in a month specified through user input. However, each day is logged twice to the console, regardless which month is chosen:

"Day:", 1
"Day:", 1
"Day:", 2
"Day:", 2

var month = prompt("enter which month of the year 1 to 12", 6);
for (var days = 1; days <= 31; days++) {
  if ((month == 4 || month == 6 || month == 9 || month == 11) && days == 31) continue
  console.log('Day:', days);
  if (month == 2 && days == 28) break
  console.log('Day:', days);
}

2
  • your if statement, you did not use curly brackets, so the two console.log() are always executed.
    – GrafiCode
    Aug 25, 2022 at 9:47
  • maybe it should be: if ((month == 4 || month == 6 || month == 9 || month == 11) && days == 31) { console.log('Day:', days); continue; } else if (month == 2 && days == 28) { console.log('Day:', days); break; }
    – GrafiCode
    Aug 25, 2022 at 9:48

2 Answers 2

0

    var month=prompt ("enter which month of the year 1 to 12", 6);

    for(var days=1; days<=31; days++) {
      if((month==4 || month==6 || month==9 || month==11) && days==31)break;
      if(month==2 && days==28)break
      console.log('Day:',days);
    }

0

but my output print twice in console like day1 repeats twice

Without {}, if statements only affect the immediately following line which in this case would be just continue and break as you have set them inline.

I think the program can be improved to factor in for the leap year value.

var month = prompt("enter which month of the year 1 to 12", 6);

if (month < 1 || month > 12) {
    alert('Please enter a valid month');
}

// to factor for the leap year instead of hardcoding 28 for Feb
var currentYear = new Date().getFullYear();
var daysInMonth = new Date(currentYear, month, 0).getDate(); 

for (var days = 1; days <= daysInMonth; days++) {
    console.log('Day:', days);
}

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.