Skip to content

Leap year Question in Javascript using nested if-else

In the nested if statement, I have given all the conditions. But some leap years are not being shown as Leap year. For eg: 2000 is coming as a leap year, but year like 2016, 2020 aren’t being considered as a leap year. Please Help.

var y = prompt("Enter the year");

if (y % 4 === 0) {
  if (y % 100 === 0) {
    if (y % 400 === 0) {
      alert(y + " is a leap year");
    } else {
      alert(y + " is not a leap year");
    }
  } else {
    alert(y + " is not a leap year");
  }
} else {
  alert(y + " is not a leap year");
}

Answer

If the year is divisible by 100, you need to check if the year is divisible by 400 too. But what you’re missing is, if year is not divisible by 100 but divisible by 4, it is a leap year already. so you need to edit your code like following:

if (y % 4 === 0) {
  if (y % 100 === 0) {
    if (y % 400 === 0) {
      alert(y + " is a leap year");
    } else {
      alert(y + " is not a leap year");
    }
  } else {
    //if year is divisible by 4 but not 100, it is a leap year
    alert(y + " is a leap year");
  }
} else {
  alert(y + " is not a leap year");
}