Categories
JavaScript Answers

How to Check if a Year is a Leap Year in JavaScript?

Spread the love

Sometimes, we want to check if a year is a leap year in JavaScript.

In this article, we’ll look at how to check if a year is a leap year in JavaScript.

Check if a Year is a Leap Year in JavaScript

To check if a year is a leap year in JavaScript, we can check if the year is evenly divisible by 4 and it isn’t evenly divisible by 100, or the year is evenly divisible by 400.

For instance, we can write:

const leapYear = (year) => {  
  return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);  
}  
console.log(leapYear(1900))  
console.log(leapYear(2016))

to create the leapYear function that does the checks.

We check if year is evenly divisible by 4 and it isn’t evenly divisible by 100 with:

(year % 4 === 0) && (year % 100 !== 0)

And we check if year is evenly divisible by 400 with:

year % 400 === 0

We join both expressions together with the OR operator.

Therefore, the first console log should log false since it’s evenly divisble by 4 but not evenly divisble by 100, and it’s not evenly divisible by 400.

On the other hand, the 2nd console log should log true , since it’s evenly divisible by 4 and it’s not evenly divisible by 100.

Conclusion

To check if a year is a leap year in JavaScript, we can check if the year is evenly divisible by 4 and it isn’t evenly divisible by 100, or the year is evenly divisible by 400.

Leave a Reply

Your email address will not be published. Required fields are marked *