JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

Chapter 3

In this chapter we looked at how JavaScript can make decisions based on conditions. We also looked at loops and functions.

Question 1

Q: 

 

A junior programmer comes to you with some code that appears not to work. Can you spot where he went wrong? Give him a hand and correct the mistakes.

var userAge = prompt("Please enter your age");
    
if (userAge = 0);
{
   alert("So you're a baby!");
}
else if ( userAge < 0 | userAge > 200)
   alert("I think you may be lying about your age");
else
{
   alert("That's a good age");
}

A: Oh dear, our junior programmer is having a bad day! There are two mistakes on the line
if (userAge = 0);

First, he has only one equals sign instead of two in the if's condition, which means userAge will be assigned the value of zero rather than userAge being compared to zero. The second fault is the semicolon at the end of the line—statements such as if and loops such as for and while don't require semicolons. The general rule is that if the statement has an associated block (that is, code in curly braces) then no semicolon is needed. So the line should be

if (userAge == 0)

The next two faults are with these lines:

else if ( userAge < 0 | userAge > 200)
   alert("I think you may be lying about your age");
else

The junior programmer's condition is asking if userAge is less than zero OR userAge is greater than 200. The correct operator for a Boolean OR is ||, but the programmer has only used one |. Secondly, the alert() function should to be inside a block, which we indicate with curly braces.

else if ( userAge < 0 || userAge > 200)
{
   alert("I think you may be lying about your age");
}
else

Question 2

Q: 

 

Using document.write(), write code that displays the results of the 12 times table. Its output should be the results of the calculations.

12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
.....
12 * 11 = 132
12 * 12 = 144

A: 
<html>
<body>
<script language=JavaScript>
var timesTable = 12;
var timesBy;
    
for (timesBy = 1; timesBy < 13; timesBy++)
{
   document.write(timesTable + " * " + timesBy + " = " + timesBy * timesTable +
      "<br>");
}
</script>
</body>
</html>

Save this as ch03_q2.htm.

We use a for loop to calculate from 1 * 12 up to 12 * 12. The results are written to the page with document.write(). What's important to note here is the effect of the order of precedence; the concatenation operator (the +) has a lower order of precedence than the multiplication operator, *. This means that the timesBy * timesTable is done before the concatenation, which is the result we want. If this were not the case, we'd have to put the calculation in parentheses to raise its order of precedence.

Question 3

Q: 

 

Change the code of Question 2 so that it's a function that takes as parameters the times table required and what values it should start and end at. So we might want the 4 times table displayed starting with 4 * 4 and ending at 4 * 9.

A: 
<html>
<body>
<script language=JavaScript>
function writeTimesTable(timesTable, timesByStart, timesByEnd)
{
   for (;timesByStart <= timesByEnd; timesByStart++)
   {
      document.write(timesTable + " * " + timesByStart + " = " +
         timesByStart * timesTable + "<br>");
   }
}
    
writeTimesTable(4,4,9);
</script>
</body>
</html>

Save this as ch03_q3.htm.

We've declared our function, calling it writeTimesTable(), and given it three parameters. The first is the times table we want to write, the second is the start point, and the third is the number it should go up to.

We've modified our for loop. First we don't need to initialize any variables, so the initialization part is left blank—we still need to put a semicolon in, but there's no code before it. The for loop continues while the timesByStart parameter is less than or equal to the timesByEnd parameter. You can see that, as with a variable, we can modify parameters—in this case, timesByStart is incremented by one for each iteration through the loop.

The code to display the times table is much the same. For the function's code to be executed, we now actually need to call it, which we do in the line

writeTimesTable(4,4,9);

This will write the 4 times table starting at four times four and ending at nine times four.

Question 4

Q: 

 

Modify the code of Question 3 to request the times table to be displayed from the user; the code should continue to request and display times tables until the user enters -1. Additionally, do a check to make sure that the user is entering a valid number; if it's not valid, ask her to re-enter it.

A: 
<html>
<body>
<script language=JavaScript>
    
function writeTimesTable(timesTable, timesByStart, timesByEnd)
{
   for (;timesByStart <= timesByEnd; timesByStart++)
   {
      document.write(timesTable + " * " + timesByStart + " = " +
         timesByStart * timesTable + "<br>");
   }
}
    
var timesTable;
    
while ( (timesTable = prompt("Enter the times table",-1)) != -1)
{
   while (isNaN(timesTable) == true)
   {
    timesTable = prompt(timesTable + " is not a valid number, please retry",-1);

   }
    
   if (timesTable == -1)
   {
      break;
   }
    
   document.write("<br>The " + timesTable + " times table<br>");
   writeTimesTable(timesTable,1,12);
    
}
</script>
</body>
</html>

Save this as ch03_q4.htm.

The function remains the same, so let's look at the new code. The first change from Question 3 is that we declare a variable, timesTable, and then initialize it in the condition of the first while loop. This may seem like a strange thing to do at first, but it does work. The code in parentheses inside the while loop's condition

((timesTable = prompt("Enter the times table",-1))

is executed first because its order of precedence has been raised by the parentheses. This will return a value, and it is this value that is compared to -1. If it's not –1, then the while condition is true, and the body of the loop executes. Otherwise it's skipped over, and nothing else happens in this page.

In a second while loop nested inside the first, we check to see that the value the user has entered is actually a number using the function isNaN(). If it's not, then we prompt the user to try again, and this will continue until a valid number is entered.

If the user had entered an invalid value initially, then in the second while loop she may have entered –1, so following the while is an if statement that checks to see if -1 has been entered. If it has, we break out of the while loop; otherwise the writeTimesTable() function is called.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©

R7