Leap Year Check
Program to check if a year is a leap year
JavaScript Leap Year Check Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Leap year rules:
// 1. Divisible by 4 → Leap year
// 2. BUT if divisible by 100 → NOT leap year
// 3. UNLESS divisible by 400 → Leap year
function isLeapYear(year) {
if (year % 400 === 0) {
return true;
} else if (year % 100 === 0) {
return false;
} else if (year % 4 === 0) {
return true;
} else {
return false;
}
}
// Test cases
console.log("2000:", isLeapYear(2000) ? "Leap year" : "Not leap year");
console.log("1900:", isLeapYear(1900) ? "Leap year" : "Not leap year");
console.log("2024:", isLeapYear(2024) ? "Leap year" : "Not leap year");
console.log("2023:", isLeapYear(2023) ? "Leap year" : "Not leap year");
// Method 2: Single expression
function isLeapYear2(year) {
return (year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0);
}
console.log("\nUsing single expression:");
console.log("2000:", isLeapYear2(2000));
console.log("1900:", isLeapYear2(1900));
console.log("2024:", isLeapYear2(2024));
// Method 3: Using ternary
function isLeapYear3(year) {
return year % 400 === 0 ? true :
year % 100 === 0 ? false :
year % 4 === 0 ? true : false;
}
console.log("\nUsing ternary:");
console.log("2000:", isLeapYear3(2000));
console.log("2023:", isLeapYear3(2023));2000: Leap year 1900: Not leap year 2024: Leap year 2023: Not leap year Using single expression: 2000: true 1900: false 2024: true Using ternary: 2000: true 2023: false
Understanding Leap Year Check
This program demonstrates leap year logic with multiple conditions.
Leap Year Rules
A year is a leap year if:
Leap year
Leap year
Not a leap year
Examples:
Method 1: If-Else Chain
Clear, step-by-step logic:
if (year % 400 === 0) return true;
else if (year % 100 === 0) return false;
else if (year % 4 === 0) return true;
else return false;
Method 2: Single Expression
Combining conditions with logical operators:
return (year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0);Logical Operators:
||: OR - at least one true&&: AND - both must be true!: NOT - reverses booleanMethod 3: Nested Ternary
Compact but less readable:
year % 100 === 0 ? false :
year % 4 === 0 ? true : false;
return year % 400 === 0 ? true : Why Leap Years?
When to Use:
-
If-else
: Most readable, learning
-
Single expression
: Concise, efficient
-
Ternary
: Compact, but harder to read
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.