export function isLeap(year) {
return new Date(year, 1, 29).getMonth() == 1;
}
Caution
This approach may be considered a "cheat" for this exercise.
By creating a new
Date
from February 29th for the year, you can see if the month is still February.
If it is, then the year is a leap year.
This is checked by using the getMonth method of the Date
object.
Note
Note that the value returned from the getMonth
method is zero-based, meaning that February is 1
, not 2
.
Shortening
When the body of a function is a single expression, the function can be implemented as an arrow function, like so
export const isLeap = (year) => new Date(year, 1, 29).getMonth() == 1;
Notice that return
and the curly braces are not needed.
13th Nov 2024
·
Found it useful?