Check If Year Is Leap Year in JavaScript

Check if year is leap year in javascript

function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

How to determine whether a year is a leap year in JavaScript

You could just check the feburary 29th of the given year and see if its changes to march 1st.

const date = new Date(this.year, 1, 29);
return date.getMonth() === 1;

If getMonth() returns 1, then its still feburary which means its leap year.

Writing a JavaScript program to calculate a leap year

Your function is ok, except for a simple thing: you are missing the year parameter!

function isLeapYear(year) {
return year % 4 == 0 &&
(year % 100 !== 0 || year % 400 === 0);
}

But, with your extended syntax is ok too:

function isLeapYear(year) {
if(year % 4 == 0)
{
if(year % 100 == 0)
{
if(year % 400 == 0)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
else
{
return false;
}
}

isLeapYear(1900) yields false, as expected, 2000 true, 1996 true, 1997 false.

Seems legit to me.

Leap year Question in Javascript using nested if-else

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");
}


Related Topics



Leave a reply



Submit