Working with conditional statements

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 (condition) {
   JavaScript commands if true
}

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";
}

If the input does not correspond to a day number, a warning is returned. Try how it works:

Enter n:    

The following function takes as a parameter an integer number in the range 0..99 and outputs it in a "two-digit" form. That is, if the parameter is in the range 0..9, then it is output with a preceeding 0.

function twoDigit(n)
{
   if (n < 10) 
      return "0" + n;
   else 
      return n;
}

Try how it works:

Enter n:    

Note that a zero is also added in front of the number even if n is non-negative, or a non-integer which is smaller than 10.

This function can be used in a digital clock for displaying the amount of minutes and seconds in a two-digit form as it is standard in all modern digital clocks. The time is displayed in the "military" format.

The above digital clock can be produced by the following code:

HTML/JavaScript codeComments
<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