JavaScript Editor Free JavaScript Editor     JavaScript Debugger 

Main Page

Previous Page
Next Page

4.4. Flow-Control Statements

My first job straight out of college was working on an order-entry system that was developed by the elves at Bell Labs. Needless to say, I found myself in the Promised Land; although the salary was only alright, the tools and some of the code were brilliant. Notice that I said "some of the code." There was also some code that really, really stunk.

One particular "utility" comes to mind. Its purpose was to simulate an order being sent to manufacturing and billing. It had absolutely no conditions or loopsjust the brute-force changing of the order status, totally disregarding whether the order was ready for transmittal. I'm not 100 percent sure why, but this inelegant code bothers me to this day.

One possible reason could be that I visualize code as a river with currents and eddies. As with a river, the flow of the program slows down and speeds up, depending upon the existing conditions. In my mind, I can almost see the flow following a particular channel, branching left or right and occasionally looping back upon itself. Maybe this is a strange way to look at it, but I consider flow-control statements to be elegant.

4.4.1. Conditionals

The granddaddy of all conditional statements has to be the if statement. In some form, the if statement is present in every programming language that I've ever used, seen, read about, or just plain stumbled across. Because of JavaScript's C roots, the if statement syntax is like a function with the condition being enclosed in parenthesis and the following statement being executed only when the condition is TRue. Sometimes there is an else followed by the statement to execute when the condition is false, and sometimes there isn't. When multiple statements need to be executed, they are enclosed in curly braces. Listing 4-3 shows the basics.

Listing 4-3. The Basics of the JavaScript if Statement

if(a == 1)
  alert('a is one');
else {
  alert('a is not one');

  if(b == 1) {
    if(c == 1)
      alert('Both b and c are one');
  } else
    alert('b is not one');

Almost as if it were cloned right from the pages of Kernighan and Ritchie's The C Programming Language (Prentice Hall, 1988), the conditional operator is a ternary operator, essentially an entire if statement/else statement shrunken into a convenient package for those of us who suffer from the sausage fingers affliction. The only problem is that many developers consider it too confusing and, therefore, avoid it. But it isn't really that hard; just remember that it breaks down in the following manner:

room != 'y2' ? 'xyzzy' : 'plugh'

Most often you'll see the result assigned to a variable like this:

magicWord =  room != 'y2' ? 'xyzzy' : 'plugh'

To those of you with mad scientist tendencies, the answer is, yes, conditional operators can be nested. The answer to the next question is also, yes, I have nested conditional operators.

The next four flow-control statements go together; in fact, you'll never see three of them by themselves. I am referring to the conditional structure that is known in various programming languages by a number of names, including case, select, choose, or switch, as it is called in JavaScript.

The switch statement evaluates a series of conditions until a condition is met. When this happens, execution begins at the case statement with the true condition. If none of the conditions is true, the execution begins at the default statement or after the switch, if there is no default statement. Listing 4-4 shows the basic structure of the switch statement.

Listing 4-4. Basic Structure of the switch Statement

switch(number) {

    alert('odd < 5');

    alert('even < 6');



In addition to the "standard" version of the switch statement shown in Listing 4-4, there is a little known variant. Instead of using a variable as the expression, true or false can be used. This allows for the possibility of using a switch statement instead of a series of nested if statements, as Listing 4-5 illustrates.

Listing 4-5. A switch Statement Acting Like a Series of Nested if Statements

switch(true) {
  case(number == 0):
  case(color == 'red'):

  case(color == 'green'):

  case(color == 'blue'):

  case((color % 2) == 0):



4.4.2. Looping

The purpose of looping in programs is to execute a series of statements repeatedly, thus cutting down on the required lines to code. This reduction in the number of lines has the advantage of improving the overall readability. In addition, loops allow for a variable number of executions. Personally, loops mean that I don't have to type any more than I have to, but, hey, I'm a hunt-and-peck typist.

It has been a while since CSC 100, "Introduction to Computer Science," but if I remember correctly, the for loop was the first type of looping structure taught. Most likely the reason for this is that it is really hard to mess it up, even for virgin programmers. A block of code is executed a specific number of times, incrementing a variable for each iteration.

The for/in loop is a close relative of the for loop. However, unlike the for loop, which specifies the number of iterations using a numeric value, an object is used. The really unfortunate thing about the for/in loop is that most people forget it exists, myself included. Listing 4-6 has several examples of both for and for/in loops.

Listing 4-6. Examples of for and for/in Loops

var factorial = 1;
var numbers = new Array(1,2,3,4,5);
var index;

for(var i=1;i < 6;i++)
  factorial *= i;

factorial = 1;

for(var i=5;i > 0;i)
  factorial *= i;

factorial = 1;

for(index in numbers)
  factorial *= numbers[index];


Because they are so similar in function, the while loop and the do/while loop offer a quandary concerning which to use. They both execute a block of instructions while a condition is TRue. So why are there two different loops, you ask? Go on, ask; I'll wait.

The reason there are two different loops is that one tests before executing the block of code, and the other tests after executing the block of code. The while loop performs the test and then executes the code block only if the condition is true. Iteration continues until the condition is no longer TRue, at which time execution continues with the code immediately following the loop.

On the other hand, the do/while loop executes the code block before performing the test. Because the test is performed after the execution of the code block, it guarantees that the code block will be executed at least once. This is quite useful when it is necessary to execute the code block once, regardless of whether the condition is true.

The majority of times that I code a loop, it is because I'm looking for something. Where I'm looking isn't important, although it is usually either in an array or in the DOM. However, what is important is that I need to find it. So I'll write a little routine that loops through whatever, looking for something. Let's say that there are 600 whatevers and I find what I'm looking for at number 20. Wouldn't it be nice to be able to stop looking?

It is possible; remember the break statement from the switch? It also terminates a loop-dropping execution to the statement immediately following the loop. Heck, it is even elegant.

But what if you don't want to exit the loop, but rather continue with the next iteration? Then you use the continue statement, which causes the current iteration to stop and the next iteration to begin. It is sort of like going back for a second helping of the entreé when you haven't finished your vegetables, but hey, unlike your mother, JavaScript doesn't complain.

One more issue arises with exiting loops; JavaScript allows labels to be placed on statements, like looping statements. This provides a way to refer to the statement from elsewhere in the script. This means that a break or continue can refer to a specific loop so that it is possible to break or continue an outer loop from an inner loop. Listing 4-7 gives an example of how this worksa useless example, but an example nonetheless.

Listing 4-7. A Useless Example of Using break and continue to Refer to a Specific Loop

var result = 1;

Iloop: for(var i=0;i < 5;i++)
Jloop:   for(var j=0;j < 5;j++)
           if(j == 2)
             break Jloop;
Kloop:       for(var k=0;k < 5;k++)
               if(k == 3)
                 continue Iloop;
                 result += k;

Previous Page
Next Page . Bitcoin Dice Site

JavaScript Editor Free JavaScript Editor     JavaScript Debugger