Previous: Working with Variables Next: Understanding JavaScript Objects

Controlling Your JavaScript

So far you've seen quite a few of the basic JavaScript programmer's tools, including variables, functions, assignments, and math. The next step is using those items together with some of JavaScript's built-in statements to create meaningful expressions that help you get things done in your scripts. This section discusses some of the statements you use to control the script.

If you have any experience with programming languages, JavaScript's statements should be familiar: the if...else construct and the loop statements for, while, break, and continue.

The key to many of these statements is called the condition, which is simply a bit of JavaScript code that needs to be evaluated before your script decides what to do next. You can think of a condition's logic as, "If something is true, then something else will happen." A similar condition might be, "Until something is true, continue trying to make it true." And so on.

Often, these conditions require a comparison of some kind—is one value equal to another, or is a value greater than another? That works together with the conditional to create a statement along the lines of, "If x is greater than y, then return the value of x."

So, before you look at JavaScript conditional statements, take a look at the comparison operators that JavaScript recognizes.

Comparison Operators

Comparisons are generally enclosed in parentheses, and they are always small snippets of code designed to evaluate as true or false. For instance, the following is a conditional statement:

(x == 1)

This may look like an assignment, but note carefully that there are two equal signs. That means this is a comparison to see if the two values really are equal to one another. If x does equal 1, this condition is true.

Now, believe it or not, an assignment can also have a value—it's always true. The following condition will always evaluate to true, because it's an assignment:

(errorLevel = 1)

Although it may seem to make sense to use an equal sign to create the "does x equal 1" comparison, if you don't use the proper operator, you'll accidentally change it to "set x equal to 1." That isn't what you want. In this instance, you actually need to use the comparison operator == for this condition.

Table 1 shows a listing of the comparison operators.

Table 1 Comparison Operators in JavaScript

Operator

Meaning

Example

Is True When

==

Equal to

x == y

x equals y

!=

Not equal to

x != y

x is not equal to y

>

Greater than

x > y

x is greater than y

<

Less than

x < y

x is less than y

>=

Greater than or equal to

x >= y

x is greater than or equals y

<=

Less than or equal to

x <= y

x is less than or equals y


All these operators can be used to create expressions that can be evaluated as either true or false. Some examples are

(countVar == 5)
(testAver > 85)
(itemType != "shirt")

As the examples show, comparisons can test strings as well as numerical values. When a comparison is evaluated, the actual comparison itself—the parentheses and all—is set to either true or false. It's given a value that could be assigned to a variable if necessary. Just remember to picture those parentheses as replaced by "true" or "false" when you're scripting and you'll have a good sense of how the comparisons are actually working.

The if...else Condition

So how do you put these comparisons and operators to use? JavaScript offers the if...else conditional statement as a way to create either/or situations in your script. Here's how it works:

if (condition) {
 script statements }
else {
 other statements }

The condition can be any comparison that evaluates to either true or false. The statements can be any valid JavaScript statements. For example:

if (x == 5) {
 document.writeln("The variable X equals 5.");
 return;
 }
 else {
 document.writeln("The variable X does not equal 5.")
 }

The else statement and related statements are not required if you simply want the if statements to be skipped and the rest of the function executed. An example might be

if (totalValue == 0) {
  return (0);
  }

In this case, if the condition is false (totalValue does not equal 0), the if statement is skipped completely and anything that comes after it is executed. If the condition is true, the return (0); command is executed and this particular function has ended abruptly.

Looping Conditionals

The next two conditional types are used to create loops—script constructs that repeat until a condition is met. These loop statements are for and while.

A for loop looks like this:

for (counter variable; condition; increment_counter variable) {
   JavaScript statements
   }

This is how it works:

  1. You'll generally start a for loop by initializing your counter variable.

  2. Then, you'll evaluate the counter within a condition to see if it's reached a certain level.

  3. If it hasn't, the loop will perform the enclosed statements.

  4. Once the statements have been performed, the counter variable is incremented.

  5. If the counter has reached your predetermined value, the for loop ends. If not, the loop continues with step 2.

For example:

for (x=0; x<10; x=x+1) {
  totalNum = 2 * x;
  document.writeln ("Two times " + x + " equals " + totalNum + "<br \/>");
  }

You start by initializing a counter variable (x=0) and then evaluating the counter in a conditional statement (x<10). If the condition is true, the loop will perform the enclosed scripting. Then it will increment the counter—in this case, add 1 to it. The loop begins again and the new value of x is compared to 10; when the counter reaches 10, the loop ends.

The while loop is similar to the for loop, except that it offers a little more freedom. It's used for a great variety of conditions. The basic while loop looks like

while (condition) {
 JavaScript statements
 }

As long as the condition evaluates to true, the loop will continue. An example would be the following:

x = 0;
while (x <= 5) {
  x = x + 1;
  document.write (X now equals " + x + "<br \/>")
  }

As long as the condition remains true, the while statement will continue to loop. In fact, the risk with while statements is that they can become infinite loops if the expression never evaluates to false. Here's a common mistake:

while (x = 5) {
 x = x + 1;
 document.write (X now equals " + x + "<br \/>")
 }

The condition is actually an assignment, not a comparison, so it will always evaluate to true. In this example, the loop would continue indefinitely, and the output would always be X now equals 6.

Break and Continue Your Loops

Two other keywords, break and continue, can be used in for and while loops to change the way a loop operates when certain conditions occur.

break is ideally used when you're not sure which values are coming—for instance, when the values are being input by a user, via XHTML form elements. Consider a bit of script like this:

for (x=0; x < 10; x=x+1) {
  z = getInput ();
  if (z == x)
    break;
  }

In this case, a function called getInput() is being called. Assuming that function asks the user for a number and that number is assigned to z, the break occurs if the values of z and x happen to be the same. Otherwise, the for loop continues until x reaches 10.

The continue statement is used within a loop to skip a particular increment. For instance:

<script>
var x = 0
while (x < 10) {
  x = x + 1;
  if (x == 5) continue;
  document.writeln (x + " does not equal 5. <br \/>");
  }
</script>

In this case, when the condition (x == 5) evaluates to true, the continue statement will cause the loop to move directly back to the while statement, thus skipping over the last line that writes out the statement. When the condition is false, as it will be most of the time, the last line will execute, resulting in another line of XHTML text and markup.

Loops and Arrays

Although there are plenty of reasons to use loops in your scripting, one reason that may not have jumped out at you yet is working with arrays. It turns out that loops and arrays are natural helpmates. Loops are great at counting from one number to the next, and arrays store multiple values using a numerical index.

Let's consider the example of a while loop designed to extract values from an array:

<script type="text/javascript">
<!-- Hide scripting
student = new Array("Bill", "Wendy", "Susan", "Barry", "Olga", "Narice");
numStudents = (student.length);
document.writeln ("There are " + numStudents + " students in the class <br \/>");
var x = 0;
while (x < numStudents) {
  document.writeln ("Student #" + (x+1) + ": " + student[x] + "<br \/>");
  x++;
}
// end hiding -->
</script>

Because of the funny way arrays work, we need to do a little math with the x variable. It's used to count through the while loop, as well as to fill in with the student number and as the index for the array. Because student #1 equals index [0], we need to change the student number to (x+1). Otherwise, everything else hums along swimmingly, as you can see in Figure 5.

Figure 5 Loops make a lot of sense when you need to work with arrays.

Previous: Working with Variables Next: Understanding JavaScript Objects