JS Example for Beginners: JavaScript Program to Check Leap Year

Hits: 7

(JavaScript programming Example for Beginners)

JavaScript Program to Check Leap Year

In this example, you will learn to write a JavaScript program that will check if a year is leap year or not.


A year is a leap year if the following conditions are satisfied:

  1. The year is multiple of 400.
  2. The year is multiple of 4 and not multiple of 100.

Example 1: Check Leap Year using Condition

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

    //three conditions to find out the leap year
    if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {
        console.log(year + ' is a leap year');
    } else {
        console.log(year + ' is not a leap year');
    }
}

// take input
let year = prompt('Enter a year:');

checkLeapYear(year);

 

Output

Enter a year: 2000
2000 is a leap year

In the above program, the three conditions are checked to determine if the year is a leap year or not.

The % operator returns the remainder of the division.


Example 2: Check Leap Year using newDate()

// program to check leap year
function checkLeapYear(year) {
    let 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');
    }
}

// take input
let year = prompt('Enter a year:');

checkLeapYear(year);

Output

Enter a year: 2000
2000 is a leap year

In the above program, the month of February is checked if it contains 29 days.

If a month of February contains 29 days, it will be a leap year.

The new Date(2000, 1, 29) gives the date and time according to the specified arguments.

Tue Feb 29 2000 00:00:00 GMT+0545 (+0545)

The getDate() method returns the day of the month.

 

 

JS Example for Beginners: JavaScript Program to Check Leap Year

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.