Home Programs How to Check if its a Leap Year in JavaScript

How to Check if its a Leap Year in JavaScript

In this example we check if a year is a leap year

Some examples use a formula to check if a year is a leap year, this example checks if the month of February contains 29 days in the year specified

Example 1

// program to check leap year
function checkLeapYear(year) 
{

    const leap = new Date(year, 1, 29).getDate() === 29;
    if (leap) 
	{
        console.log(year + ' is a leap year');
    } 
	else 
	{
        console.log(year + ' is not a leap year');
    }
}

// remove comment to take input
// const year = prompt('Enter a year:');
checkLeapYear(2000);
checkLeapYear(2002);
checkLeapYear(2004);

 

When you run this you will see something like this

2000 is a leap year
2002 is not a leap year
2004 is a leap year

You can remove the comment to take user input like this

 

// program to check leap year
function checkLeapYear(year) 
{

    const leap = new Date(year, 1, 29).getDate() === 29;
    if (leap) 
	{
        console.log(year + ' is a leap year');
    } 
	else 
	{
        console.log(year + ' is not a leap year');
    }
}

// remove comment to take input
const year = prompt('Enter a year:');
checkLeapYear(year);

 

You may also like