A conditional statement is the one that runs only when specific conditions are satisfied. An If..Else statement has the following syntax:
if (condition) { JavaScript commands if true } else { JavaScript commands if false }
The If..Else statement can be used in a shortened version with the "else"-part omitted. That is,
If there is just one JavaScript command to be executed in the conditional statement, the braces surrounding it can be omitted.
The following function takes an integer parameter n in the range between 0 and 6 and returns the name of the corresponding day of the week:
function toName(n) { if (n == 0) return "Sunday"; if (n == 1) return "Monday"; if (n == 2) return "Tuesday"; if (n == 3) return "Wednesday"; if (n == 4) return "Thursday"; if (n == 5) return "Friday"; if (n == 6) return "Saturday"; return "illegal parameter"; }
The above digital clock can be produced by the following code:
HTML/JavaScript code | Comments |
---|---|
<form name="clock" action=""> <input type="text" name="display" size="8"> </form> <script type="text/javascript"> function twoDigit(n) { if (n < 10) return "0" + n; else return n; } function setClock() { var ddd = new Date(); document.clock.display.value = ddd.getHours() + ":" + twoDig(ddd.getMinutes()) + ":" + twoDig(ddd.getSeconds()); } setInterval("setClock()",1000); </script> |
opening the form for the clock display text field for the clock display closing the clock display form opening JavaScript the twoDigit function described above another function that sets up the clock creating the Date object setting up hours, ... minutes, ... and seconds calling the last function every second closing JavaScript |