JavaScript Control Structures

The control structures in JavaScript are very similar to those of C++.

Let's look at the following example:

<html>
<head>
    <title>Example 1</title>
<script>
 function max(a, b, box)
 {
  if (a > b)
   box.value = "First number is bigger";
  else if (a < b)
   box.value = "Second number is bigger";
  else
   box.value = "Equality";
 }
</script>
</head>
<body>
<form>
Number 1 <input type="text" name="num1">
<br> Number 2 <input type="text" name="num2">
<br> <input type="button" value="Get Larger"
            onClick="max(num1.value, num2.value, text1);">
<input type=text size=40 name=text1>
</form>
<p>
<a href="js3.htm#ex1"> Go Back </a>
</body>
</html>

This script sort of works, but notice that it thinks that 9 is bigger than 312! Why is that? Because the value of a text field is String by default, so the comparison is a String comparison!

Unlike C++, it is legal to compare Strings with the usual comparison operators, which are:

Here's a better version:

<html>
<head>
    <title>Example 2</title>
<script>
 function max(a, b, box)
 {
  if (a > b)
   box.value = "First number is bigger";
  else if (a < b)
   box.value = "Second number is bigger";
  else
   box.value = "Equality";
 }
</script>
</head>
<body>
<form>
Number 1 <input type="text" name="num1">
<br> Number 2 <input type="text" name="num2">
<br> <input type="button" value="Get Larger"
            onClick="max(parseFloat(num1.value), parseFloat(num2.value), text1);">
<input type=text size=40 name=text1>
</form>
<p>
<a href="js3.htm#ex2"> Go Back </a>
</body>
</html>

As in C++, the general form of an if statement is:

if (conditional expression)
{
    statements if true;
}

And you're allowed to have else clauses:

if (conditional expression)
{
    statements if true;
}
else
{
    statements if false;
}

And you can have as many "else if"s as you like:

if (conditional expression)
{
    statements if first condition expression is true;
}
else if (conditional expression)
{
    statements if second condition expression is true;
}
else
{
    statements if false;
}

The braces are necessary if there is more than one statement in the instructions.

Unlike C++, the value of the conditional expression is a Boolean, not an integer! But consider the following example:

<html>
<head>
    <title>Example 2</title>
<script>
 function equal1(a, b, box)
 {
  if (a.value = b.value)
   box.value = "Equal";
  else
   box.value = "Not Equal";
 }
 function equal2(box)
 {
  if (true)
   box.value = "Always Say Equal";
  else
   box.value = "Never Say Not Equal";
 }
 function equal3(box)
 {
  if (0)
   box.value = "Never Say Equal";
  else
   box.value = "Always Say Not Equal";
 }
</script>
</head>
<body>
<form>
Number 1 <input type="text" name="num1">
<br> Number 2 <input type="text" name="num2">
<br> <input type="button" value="Equal1" onClick="equal1(num1, num2, text1);">
<input type="button" value="Equal2" onClick="equal2(text1);">
<input type="button" value="Equal3" onClick="equal3(text1);">
<input type=text size=40 name=text1>
</form>
<p>
<a href="js3.htm#ex3"> Go Back </a>
</body>
</html>

In the first function, we can put an assignment operator in the conditional expression. The value of the right hand operand is the value that gets assigned. And then, if that value is non-zero, the value of the conditional expression is true. This is just like C++.

But in the second function, the constant true can be the conditional expression (unlike C++). The constant false could also be here.

Finally in the third function, the constant 0 is the conditional expression. This evaluates to false (just like C++).


The value null can also be used in a conditional expression, to test to see if a variable or form element is empty. We use in the next example.

<html>
<head>
    <title>Example 4</title>
<script>
 function getData()
 {
  alert("Hit the Cancel on the next prompt");
  var a = prompt("Can you follow directions?","");
  if (a == null)
  {
   alert("Do you always follow directions?");
  }
  else
  {
   alert("Why don't you do what I say?");
  }
 }
 function doubled(box1, box2)
 {
  if (box1 == null)
   box2.value = "It was null";
  else if (box1 == "")
   box2.value = "It's empty!";
  else
   box2.value = box1.value * 2;
 }
</script>
</head>
<body>
<form>
<br> <input type="button" value="Click Me First" onClick="getData();">
<br><input type="text" name=op1 size=10>
* 2
<input type="button" value="=" onClick="doubled(op1, ans);">
<input type=text name=ans size=10>
</form>
<p>
<a href="js3.htm#ex4"> Go Back </a>
</body>
</html>

The value of a variable that has not been given a value is null.

But the numeric value of an empty text field is 0!


We can also use Boolean operators in the conditional expression.


Here's something you see a lot - a hot graphic that changes when the cursor is over it...

<html>
<head>
    <title>Example 5</title>
</head>
<script>
var picture1="red.jpg";
var picture2="blue.jpg";
</script>
<body>
<p>
<a href="js3.htm#ex5"
   onMouseOver="document.pic1.src='red.jpg'"
   onMouseOut="document.pic1.src='blue.jpg'">
<img src="blue.jpg" name="pic1" border=0>
Go Back
</a>
</body>
</html>

Note that an IMG command must have a name if you are going to change the src attribute of a graphic. This is true about changing an attribute of any command.


Besides alert and prompt, there is also another similar function called confirm. The confirm function returns true or false, depending upon which button you clicked. Look at this example:

<html>
<head>
    <title>Example 6</title>
<script>
var ans = confirm("Do you really want to go here?")
if (ans == false)
{
 history.go(-1);
}
</script>
</head>
<body>
<p>
<a href="js3.htm#ex6">
Go Back
</a>
</body>
</html>

Since the script is in the head, it gets loaded before the page.


Here's another example. Notice that if the value of location is changed, you go to a new page...

<html>
<head>
    <title>Example 7</title>
<script>
var ans = confirm("Do you want to go to Saint Rose instead?")
if (ans)
{
 location="http://www.strose.edu";
}
</script>
</head>
<body>
<p>
<a href="js3.htm#ex7">
Go Back
</a>
</body>
</html>


We have for loops, while loops, and do while loops in JavaScript. The one change is that the conditional expression can be either a Boolean value or an integer.

We also have a switch statement in JavaScript. The one difference is that the expression we do the switch on can be either a number or a String.

The next example quickly illustrates some of these ideas:

<html>
<head>
    <title>Example 8</title>
<script>
 function getFactorial()
 {
  var x = prompt("Enter an integer","");
  if (x == null)
   alert("Don't hit the Cancel!");
  else
  {
   answer = 1;
   for (i = 1; i <= x; i++)
   {
    answer = answer * i;
   }
   alert (x + " factorial is " + answer);
  }
 }
</script>
</head>
<body>
<form>
<br> <input type="button" value="Play Craps" onClick="window.open('ex10.htm','PlayCraps');">
<br> <input type="button" value="Astrology" onClick="window.open('ex9.htm','Astrology')">
<br> <input type="button" value="Get Factorial" onClick="getFactorial()">
</form>
<p>
<a href="js3.htm#ex8"> Go Back </a>
</body>
</html>

The getFactorial function has an example of a for loop.

Notice that clicking the other buttons causes the window.open() function to be called. The first argument of the function is the page to go to. The second argument is the name of the new window. There are other optional arguments, but we'll discuss these later.


The "Astrology" page looks like this:

<html>
<head>
   <title> Page 7 </title>
<script>
function getSignMessage()
{
 var sign = prompt("What is your birth sign?","");
 switch (sign)
 {
  case "Aquarius": case "AQUARIUS": case "aquarius":
      document.writeln("You will be lucky today!");
      break;
  case "Cancer": case "CANCER": case "cancer":
      document.writeln("You will meet your true love today!");
      break;
  case "Libra": case "LIBRA":  case "libra":
      document.writeln("You will have great success!");
      break;
 case "Pisces": case "PISCES": case "pisces":
      document.writeln("You will find your best friend today!");
      break;
 case "Gemini": case "GEMINI": case "gemini":
      document.writeln("Be wary of strangers!");
      break;
 case "Capricorn": case "CAPRICORN": case "capricorn":
      document.writeln("Do something humorous!");
      break;
 case "Taurus": case "TAURUS": case "taurus":
      document.writeln("Have fun tonight!");
      break;
 case "Leo": case "LEO": case "leo":
      document.writeln("Study tonight!");
      break;
 case "Scorpio": case "SCORPIO": case "scorpio":
      docuement.writeln("Don't eat chocolate cake for breakfast!");
      break;
 case "Sagittarius": case "SAGITTARIUS": case "sagittarius":
      document.writeln("Be careful with your finances!");
      break;
 case "Aries": case "ARIES": case "aries":
      document.writeln("Don't look behind you! It might be catching up!");
      break;
 case "Virgo": case "VIRGO": case "virgo":
      document.writeln("Be prepared for your next test!");
      break;
 default:
      document.writeln("Learn to spell!");
 }
}
</script>
</head>
<body>
<script>
 getSignMessage();
</script>
<p>
<form>
<input type=button value="good bye" onClick="window.close(); return true;">
</form>
</body>
</html>

As you can see, string values can be included in the switch.

The function window.close() causes this window to close.


In the "Craps example, we make use of a do while loop.

Also note the use of two functions:

Math.ceil() returns the value of its argument, rounded up.

Math.random() returns a random floating point  number in the range from 0 to 1.

<html>
<head>
<title> Craps </title>
<script>
function playcraps(field)
{
  var bet=prompt("How much this time?","1");
  var firstroll1 = Math.ceil(Math.random()*6);
  var firstroll2 = Math.ceil(Math.random()*6);
  var firstsum = firstroll1 + firstroll2;
  alert("You rolled " + firstsum);
  switch(firstsum)
  {
  case 7: case 11:
    alert("You win!");
    field.value = parseInt(field.value) + parseInt(bet);
    break;
  case 2: case 3: case 12:
    alert("You lose!");
    field.value = parseInt(field.value) - parseInt(bet);
    break;
  default:
    do {
      alert("You gotta keep rolling!");
      var secondroll1 = Math.ceil(Math.random()*6);
      var secondroll2 = Math.ceil(Math.random()*6);
      var secondsum = secondroll1 + secondroll2;
      alert("You rolled " + secondsum);
    } while (secondsum != firstsum && secondsum != 7);
    if (secondsum == firstsum)
    {
      alert("You win!");
      field.value = parseInt(field.value) + parseInt(bet);
    }
    else
    {
      alert("You lose!");
      field.value = parseInt(field.value) - parseInt(bet);
    }
  }
}
</script>
</head>
<body>
<center>
<font size=5>Craps</font>
</center>
Click the Button to Shoot Those Dice!
<p>
<form>
Winnings:
<input type=text name="winnings" value="0">
<p>
<input type=button value="Play Game"
 onClick="playcraps(winnings);">
</form>
</html>