JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if a year is a leap year in JavaScript?

The most basic way to check if a year is a leap year or not is to follow these rules:

  • If a year is not an end-of-century year and divisible by 4, then it is a leap year.
  • If a year is an end-of-century year and divisible by 400, then it is a leap year.
function isLeapYear(date){
  let year = date.getFullYear();
  if(year%4 === 0 && year%100 !== 0){
    return true;
  }else if(year%400 === 0){
    return true;
  }else{
    return false;
  }
}

let d1 = new Date(2020, 1, 27),
    d2 = new Date(2000, 11, 15),
    d3 = new Date(2021, 3, 2);

console.log(isLeapYear(d1)); //true
console.log(isLeapYear(d2)); //true
console.log(isLeapYear(d3)); //false

The code uses if else statement to check whether a year is a leap year or not.

The modulo operator (%) is used to get the remainder of the division.

You can also use logical OR and logical AND operators to make the code more concise.

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

Another approach is to create a Date object that represents the 29th of February. If the 29th of February exists in that year, then calling the getDate() method will return 29, and the year is called a leap year.

On the other hand, if the 29th of February does not exist in that year, then the getDate() method will return 1 because the Date class automatically changes the date to 1 and the month to March.

let d1 = new Date(2020, 1, 29);
console.log(d1.toDateString()); //Sat Feb 29 2020

if(d1.getDate() === 29){
  console.log(`${d1.getFullYear()} is a leap year.`);
}else{
  console.log(`${d1.getFullYear()} is not a leap year.`);
}

let d2 = new Date(2021, 1, 29);
console.log(d2.toDateString()); //Mon Mar 01 2021

if(d2.getDate() === 29){
  console.log(`${d2.getFullYear()} is a leap year.`);
}else{
  console.log(`${d2.getFullYear()} is not a leap year.`);
}

Output

Sat Feb 29 2020
2020 is a leap year.
Mon Mar 01 2021
2021 is not a leap year.

Recommended Posts