This program is for School / College students who are in the beginner level and wants to get a good knowledge in JavaScript.
To find the leap year, below three conditions has to be satisfied,
1. Year should be evenly divisible by 4 (year % 4 == 0)
2. AND (&&) Year should not be evenly divisible by 100 (year % 100 != 0)
3. OR (||) year should be evenly divisible by 400 (Year % 400 == 0)
if both the 1st AND 2nd condition is true OR 3rd is true then it is a Leap year.
Here is the JavaScript function to find leap year:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function check_leapyear(){ //define variables var year; //get the entered year from text box year = document.getElementById("year").value; //three conditions to find out the leap year if( (0 == year % 4) && (0 != year % 100) || (0 == year % 400) ) { alert(year+" is a leap year"); } else { alert(year+" is not a leap year"); } } |
What will you learn from this JavaScript program?
1. You will learn how to get the value of a text box using document.getElementByID()
2. How to use multiple if conditions in a single line
A complete demo program for you to check immediately:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<html> <head> <script> function check_leapyear(){ //define variables var year; //get the entered year from text box year = document.getElementById("year").value; //three conditions to find out the leap year if( (0 == year % 4) && (0 != year % 100) || (0 == year % 400) ) { alert(year+" is a leap year"); } else { alert(year+" is not a leap year"); } } </script> </head> <body> <h3>Javascript Program to find leap year</h3> <input type="text" id="year"></input> <button onclick="check_leapyear()">Check</button> <h5>By tutorialsmade.com</h5> </body> </html> |