JavaScript tutorial:
Controlling program flow

Main ways to control the program flow

The behavior of your script depends on user actions, events in the program, results of the computation and many other things. How do you tell your script to change the program flow in response to various events? The three main ways are:

Sequence. Two or more statements are executed one after the other.

Conditional branching. You test for a condition (e.g. user input), and the action to take depends on the results of the test. All conditional tests in JavaScript are Boolean, which means that the result is either true or false. Typically, you test values that are of Boolean, numeric, or string type.

Repetition/Looping. One or more statements are executed repeatedly. There must be at least one condition that allows you to break out of the loop, otherwise the program gets caught in an endless repetition. When this condition is met, the flow of execution changes.

Using sequence

Of all the ways to control the program flow, using sequence is the simplest: just list the statements to execute one after the other.

a = 5;
b = 10;
c = a + b;
alert(c);

Of course, using sequence alone would make your program very unidirectional. For an effective control over the program flow, you need to combine sequencing with conditional branching and looping.

Using conditional branching

For conditional branching, JavaScript uses if and if...else statements.

The if statement tests for a condition, and action is taken if the condition is met.
The if...else statement also specifies the action to take if the condition fails the test.

The result of the if test is Boolean: it is either true or false. If (and only if) the item between the parentheses evaluates to true, the statement or block of statements after the if is executed.
answer = prompt("Which state is Denver in?", "");
if(answer == "Colorado") alert("Hey, you know your geography!");
else alert("No way!!!");

The following example shows the if...else statements.

catWeight = parseInt(prompt("Enter the weight of your cat (in lbs)", 50));
                         
if (catWeight < 10) 
{
    alert("Perhaps you should feed it sometime");
}
else if (catWeight < 35) 
{
    alert("Cute kitty!");
}
else if (catWeight < 50) 
{
    alert ("OK... not too fat");
}
else
{
    alert("Are you sure it's a cat you've got?");
}

To run the examples, paste them into JavaScript Editor, and click the Execute button. 

Conditional operator

JavaScript supports a conditional operator, which is a shorter way of an if..else statement. It uses a question mark after the condition to be tested (rather than the word if before the condition), and specifies two alternatives, one to be used if the condition is met and one if it is not. The alternatives are separated by a colon.

In the expression (A) ? (B) : (C); if A is true, then B is returned; otherwise C is returned.

result = prompt("What is 2+2?", "");
(result=="4") ? "Yes!" : "Inventive, but y
ou need to work on your math skills";

When you run this script in JavaScript Editor, observe the status line. The Editor captures the return value of the entire script and displays it there.



Tip   If you have several conditions to be tested together, and you know that one is more likely to pass or fail than any of the others, depending on whether the tests are connected with OR (||) or AND (&&), you can speed execution of your script by putting that condition first in the conditional statement. For example, if three conditions must all be true (using && operators) and the second test fails, the third condition is not tested.

Similarly, if only one of several conditions must be true (using || operators), testing stops as soon as any one condition passes the test. This is particularly effective if the conditions to be tested involve execution of function calls or other code.

An example of the side effect of short-circuiting is that runSecond will not be executed in the following example if runFirst() returns 0 or false.

if ((runFirst() == 0) || (runSecond() == 0))
// some code  

Using repetition (loops)

There are several ways to execute a statement or block of statements repeatedly. In general, repetitive execution is called looping. It is typically controlled by a test of some variable, the value of which is changed each time the loop is executed. JavaScript supports many types of loops: for loops, for...in loops, while loops, do...while loops, and switch loops.

Using for loops

The for statement specifies a counter variable, a test condition, and an action that updates the counter. Just before each time the loop is executed (this is called one pass or one iteration of the loop), the condition is tested. After the loop is executed, the counter variable is updated before the next iteration begins.

sum = 0;
for (count = 0; count < 3; count++)
{
num = prompt("Enter a number", "");
sum+= parseInt(num);
}

alert("The sum of your 3 numbers is: " + sum);

If the condition for looping is never met, the loop is never executed at all. If the test condition is always met, an infinite loop results. While the former may be desirable in certain cases, the latter rarely is, so take care when writing your loop conditions. The following is an example of an infinite loop:

sum = 0;
while(1)
{
num = prompt("Enter a number", "");
if(num==0) break;

sum+= parseInt(num);
}

alert("The sum of your numbers is: " + sum);

To run the example, paste them into JavaScript Editor, and click the Execute button. To end the loop, enter 0 at the prompt.

Using for...in Loops

JavaScript provides a special kind of loop for stepping through all the properties of an object. The loop counter in a for...in loop steps through all indexes in the array. It is a string, not a number.

// Define a Car object
                         
function Car(make, year)
{
    this.make = make;
    this.year = year;
}
                         
                         
// Create an instance of a Car object
                         
MyCar = new Car("Ford", 2000);
                         
// List all the properties
for (prop in MyCar) 
{
    document.write(prop + " has the value " + MyCar[prop]);
}

To run the example, paste it into JavaScript Editor, and click the Execute button.

Using while loops

The while loop is very similar to a for loop. The difference is that a while loop does not have a built-in counter variable or update expression. If you already have some changing condition that is reflected in the value assigned to a variable, and you want to use it to control repetitive execution of a statement or block of statements, use a while loop.

answer = "";
                         
while(answer!="a")
{
   answer = prompt('"Type the second letter in "cat"', "");
	                         
   if(answer=="a") alert("Yes!");
	lse alert("Keep trying...");	
}
 

If you want the loop to execute at least once, use the do...while construct:

answer = "";
do
{
 	answer = prompt('"Type the second letter in "cat"', "");
	
 	if(answer=="a") alert("Yes!");
 	else alert("Keep trying");	
}while(answer!="a");          



Note:  Because while loops do not have explicit built-in counter variables, they are even more vulnerable to infinite looping than the other types. Moreover, partly because it is not necessarily easy to discover where or when the loop condition is updated, it is only too easy to write a while loop in which the condition, in fact, never does get updated. You should be extremely careful when you design while loops.


Using break and continue statements

JavaScript provides a statement to stop the execution of a loop. The break statement can be used to stop execution if some condition is met. The continue statement can be used to jump immediately to the next iteration, skipping the rest of the code block but updating the counter variable as usual if the loop is a for or for...in loop.

sum = 0;
while(1)
{
  	num = prompt("Enter an odd number", "");
 	num = parseInt(num); // Convert string to a number
	
 	if(num==0) break; // Break out of the while loop
	
 	if((num%2)==0) continue; // This is an even number, ignore it and continue
	
 	sum+=num; 
}
alert("The sum of your odd numbers is: " + sum);

To run the example, paste them into JavaScript Editor, and click the Execute button. To break out of the loop, type 0 at the prompt.

Using the switch statement

The switch statement is used as a convenient replacement for multiple if...else if statements. Only the block of code that meets the predefined test is executed. Here is an example:

date = new Date();
today = date.getDay(); // Returns the day (0=Sunday, etc)
str = "Today is ";
switch(today)
{
   case 0:
      str+="Sunday";
      break;
   case 1:
      str+="Monday";
      break;
   case 2:
      str+="Tuesday";
      break;
   case 3:
      str+="Wednesday";
      break;
   case 4:
      str+="Thursday";
      break;
   case 5:
      str+="Friday";
      break;
   case 6:
      str+="Saturday";
      break;
   default:
str+="[invalid]"; break; }
document.write(str);

To run the example, paste it into JavaScript Editor, and click the Execute button.

Next