Nick Huemmer

15 April 2022

Is It a Leap Year?

Here’s another challenge from Edabit that I solved today.

A leap year happens every four years, so it’s a year that is perfectly divisible by four. However, if the year is a multiple of 100 (1800, 1900, etc), the year must be divisible by 400.

Write a function that determines if the year is a leap year or not. Examples

leapYear(2020) ➞ true

leapYear(2021) ➞ false

leapYear(1968) ➞ true

This solution uses the conditional (ternary) operator to solve the problem. It is concise and easy to understand.

const year1 = 2020;
const year2 = 2021;
const year3 = 1600;
const year4 = 1700;

// arrow function using the ternary operator
const leapYearArrow = (year) => 
   year % 100 === 0 ? year % 400 === 0 : year % 4 === 0 


leapYearArrow(year1); // true
leapYearArrow(year2); // false
leapYearArrow(year3); // true 
leapYearArrow(year4); // false

First we have to test if the year is divisible by 100 as a first step to see if the year is a multiple of 100 and can be tested to see if it’s divisible by 400. If it’s divisible 100 and 400, then it’s a leap year. If not, then we test to see if the year is divisble by 4. If it is, then it’s a leap year. If not, then it’s not a leap year.

Surprisingly, I tried to write this solution as a longer form function declaration using if…else conditional logic and it was more difficult to figure out. I will post that solution later, after I figure it out.