Check for a leap year

“Leap year”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 4: Making Decisions: if, else & Friends teaches, and 4 tests check your answer.

The challenge

Write isLeapYear(year). A year is a leap year if it divides by 4, except years that divide by 100, which are only leap years if they also divide by 400.

Example
isLeapYear(2024)  // true
isLeapYear(1900)  // false
isLeapYear(2000)  // true

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • isLeapYear(2024) gives true
  • isLeapYear(2023) gives false
  • isLeapYear(1900) gives false
  • isLeapYear(2000) gives true

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Check the most specific rule first: divisible by 400.

Hint 2

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

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function isLeapYear(year) {
  if (year % 400 === 0) return true;
  if (year % 100 === 0) return false;
  return year % 4 === 0;
}

Learn what you need

This exercise uses what Grade 4: Making Decisions: if, else & Friends teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning