In this example, you will write a javascript program to check whether a year entered by the user is a leap year or not.
Condition for leap year:
function checkLeapYear() {
// take input using a prompt method
const year = prompt('Enter a year:');
//conditions to find out the leap year
if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
document.write(year + ' is a leap year');
} else {
document.write(year + ' is not a leap year');
}
}
checkLeapYear();
Enter a year: 2020 2020 is a leap year
<!DOCTYPE html>
<html>
<body>
<script>
function checkLeapYear() {
// fetch the input
let year=document.getElementById("year").value;
//conditions to find out the leap year
if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
document.write(year + ' is a leap year');
}
else {
document.write(year + ' is not a leap year');
}
}
</script>
<form>
Enter year <input type="number" id="year" />
<input type="button" value="submit" onclick="checkLeapYear()" />
</form>
</body>
</html>
Take input from the user i.e document.getElementById("year").value
and check if the year is satisfied with the above if
condition then a year will be a leap year.