Open In App

JavaScript Program to Check if a Given Year is Leap Year

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, we will see how to write a JavaScript program to check if a given year is a leap year. Leap year must satisfy the following conditions:

  • The year is multiple of 400.
  • The year is a multiple of 4 and not a multiple of 100.

Below are the approaches:

Approach 1: Traditional Leap Year Logic

Our approach will be to verify the leap-year conditions mentioned above.

  • First, Check the given input year is a multiple of 400. If true give output “Input year is a Leap year”.
  • If false, Check for the secondary conditions that the input year must be a multiple of 4 but not 100.
  • Then display the output accordingly.

Example 1: In this example, we will check the conditions of Leap year for previous years

Javascript




function isLeapYear(year) {
    if (
        year % 100 === 0 ? year % 400 === 0 : year % 4 === 0
    )
        console.log(" Input year:", year, "is a Leap Year");
    else
        console.log(
            " Input year:",
            year,
            "is NOT a Leap Year"
        );
}
 
let inputYear = 2020;
isLeapYear(inputYear);
inputYear = 2023;
isLeapYear(inputYear);


Output

 Input year: 2020 is a Leap Year
 Input year: 2023 is NOT a Leap Year

Example 2: In this example, we will check the conditions of Leap year for next/ upcoming years

Javascript




function isLeapYear(year) {
    if (
        year % 100 === 0 ? year % 400 === 0 : year % 4 === 0
    )
        console.log(" Input year:", year, "is a Leap Year");
    else
        console.log(
            " Input year:",
            year,
            "is NOT a Leap Year"
        );
}
 
let inputYear = 2354;
isLeapYear(inputYear);
inputYear = 2640;
isLeapYear(inputYear);


Output

 Input year: 2354 is NOT a Leap Year
 Input year: 2640 is a Leap Year

Approach 2: Using newDate()

  • A Date object is created with the given year, month (1 for February), and day (29).
  • The getMonth() method returns the month (0-indexed), and getDate() returns the day of the month.
  • If the month is still February, and the day is 29, then it is a leap year.

Example: In this example, we are using newDate().

Javascript




function isLeapYearUsingDate(year) {
// Create a new date on February 29th of the given year
let leapDate = new Date(year, 1, 29);
 
// Check if the month is still February and the date is 29
return leapDate.getMonth() === 1 && leapDate.getDate() === 29;
}
 
// Example usage:
let yearToCheck = 2024;
let result = isLeapYearUsingDate(yearToCheck);
 
console.log(result ? yearToCheck + " is a leap year." : yearToCheck + " is not a leap year.");


Output

2024 is a leap year.


Last Updated : 08 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads