[Solved] Leap Year - check whether a year is leap in JavaScript

  

5
Topic starter

Task: Write a JS function to check whether an year is leap.

Leap years are either divisible by 4 but not by 100 or are divisible by 400.

  • The input comes as a single number argument.
  • The output should be printed to the console. Print yes if the year is leap and no otherwise.

Examples:
Input:
1990

Output:
no


Input:
2000

Output:
yes


Input:
1900

Output:
no

3 Answers
4

My solution to the task:

function leapYear(input) {
    let year = input;
    let answer;
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        answer = "yes";
    } else {
        answer = "no";
    }
    console.log(answer);
}
 
leapYear(1999);
3

My solution with ternary operator:

function leapYear(year) {
 
    let leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    console.log(leap ? "yes" : "no");
}
 
leapYear(2000);
2

2 solutions from me:

function isLeapYear(year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}
 
console.log(isLeapYear(1999));
function checkY(y) {
    return ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) ? "yes" : "no";
}
console.log(checkY(2000));
Share: