Controlling Program Flow

Master the techniques of decision making and looping in JavaScript, with the help of this comprehensive tutorial.

One of the key features of all good programming languages is the ability to control the order in which actions are performed. For instance, you may want to run one piece of code if the user has selected a checkbox, but run a different piece of code if they haven't selected it. Or, you may want to run the same piece of code 10 times (for example, if you're creating a drop-down list with 10 items).

In this tutorial you'll learn how to write code to make decisions (e.g. "if the user has selected this checkbox, display this message"), and perform the same action many times (called "looping").

The if statement

The if statement allows you to run different chunks of code (or no code at all) depending on a condition or conditions. Here's a simple example:


if ( x < 10 )
{
  alert ( "x is less than 10" );
}

This code will display the alert "x is less than 10" if the value of variable x is less than 10. (If it's 10 or greater, the code within the braces ({ }) will be skipped.)

You can use the else statement to run an alternative block of code if the condition in the if statement is not met. For example:


if ( x < 10 )
{
  alert ( "x is less than 10" );
}
else
{
  alert ( "x is 10 or greater" );
}

Here's a "real world" example that displays a different message depending on which radio button has been selected. Note that you can have more than one condition by using multiple else statements.


function display_button ( )
{
  if ( document.getElementById("example1").rbutton[0].checked )
  {
    alert ( "You pressed the LEFT button!" );
  }
  else if ( document.getElementById("example1").rbutton[1].checked )
  {
    alert ( "You pressed the MIDDLE button!" );
  }
  else if ( document.getElementById("example1").rbutton[2].checked )
  {
    alert ( "You pressed the RIGHT button!" );
  }
  else
  {
    alert ( "You didn't press any button!" );
  }
}

Try it out! Select one of the following radio buttons then click the Which button did I press? link:

Which button did I press?

The switch statement

If you want to test for different values of the same variable, you can use a switch statement. The general syntax for a switch statement is as follows:


switch ( variable_name )
{
  case value1:
    action1;
    break;
  case value2:
    action2;
    break;
	.
	.
	.

  default:
    default_action;
}

In other words, you can test for different values of the variable variable_name and then execute different code (action1, action2 etc) depending on the variable's value.

Note that each case block (except the last) ends with a break statement. This ensures that after the action is performed, execution jumps outside the switch block. If the breaks were omitted, then the code in all of the case blocks would be executed in turn.

The last option, default, allows you to specify code to run if the variable's value does not match any of the values listed in the case statements.

Here's an example of switch in action. It reports, in words, which option you selected from a drop-down list:


function display_option ( )
{
  switch ( document.getElementById("example2").dropdown.selectedIndex )
  {
    case 0:
      alert ( "You selected the first option!" );
      break;
    case 1:
      alert ( "You selected the second option!" );
      break;
    case 2:
      alert ( "You selected the third option!" );
      break;
    default:
      alert ( "Error: No option was selected!" );
  }
}

Select an option from the drop-down list, then click the Which option did I select? link:

Which option did I select?

The while statement

The while statement is one of the looping statements available in JavaScript. A while loop allows you to keep executing a piece of code, as long as a certain condition is still met.

A while loop looks like this:


while ( condition )
{
  (stuff to do inside the loop)
}

As long as condition remains true, the code inside the loop will execute. After the code has executed once, the condition is tested again, and so on.

For example, this code will count up from 1 to 3 using the variable counter. The code in the loop will only run as long as counter is less than or equal to 3. Once counter reaches 4, the loop will exit.


function count_to_three ( )
{
  var counter = 1;
  while ( counter <= 3 )
  {
    alert ( "I've counted to: " + counter );
    counter++;
  }
}

Try it out! Click on the Start link below. You should see 3 alert boxes pop up, then the loop will finish.

Start

The do..while statement

The do..while statement is very similar to the while statement. The important difference is that the condition is tested after the code has executed. This allows you to run the code at least once. This is very useful if, for example, your code within the loop generates the values required for the condition test.

In this example, a "Confirm" dialog is displayed on the first pass through the loop. Then, depending on which button the user presses, the loop either continues or exits:


function cancel_to_finish ( )
{
  var confirm_result;

  do
  {
    confirm_result = confirm ( "Press Cancel to finish!" );
  } while ( confirm_result != 0 );

}

Click the Start link below to try it out!

Start

Note how it was important for us to run through the loop at least once, in order to get a value for confirm_result for the test.

The for statement

The for statement is another form of looping in JavaScript. You can think of it as a more specialized, shorthand version of the while loop.

The for loop allows you to specify the initial value of a looping variable (e.g. i), then a condition test, and finally a statement to update the loop variable, all in one statement!

This means that you can write loops that involve a counter much more easily and neatly than using a while loop. In fact the example in our while statement section above could be more succinctly written as a for loop.

Here's an example that counts from 1 to 10, placing the numbers in a string as it goes. It then displays the final string in an alert box.


function count_to_ten ( )
{
  var i;
  var output_string = "";

  for ( i=1; i<=10; i++ )
  {
    output_string += "I've counted to: " + i;
  }

  alert ( output_string );
}

Try it out by clicking on the Start link below:

Start

The for..in statement

The for..in loop is a bit different from the other loops we've seen so far. It allows you to loop through the properties of a JavaScript object.

(If you're unfamiliar with objects in JavaScript, think of them as black boxes that can have a number of properties associated with them. For example, a cat object might have a color property with a value of "black", and an ears property with a value of 2!)

The basic for..in construct looks like this:


for ( variable_name in object_name )
{
  < do stuff with the property here >
  < the current property name is stored in variable_name >
}

Note that, on each pass through the loop, the loop variable variable_name holds the name of the current property. To obtain the value of the current property, you would use the following syntax:


object_name[variable_name]

For example, this code loops through all the properties of the navigator object (a built-in JavaScript object that holds information about your browser), adds each property's name and value to a string, then displays the resulting string in an alert box:


function display_nav_props ( )
{
  var i;
  var output_string = "";

  for ( i in navigator )
  {
    output_string += "The value of " + i +
      " is: " + navigator[i] + "\n";
  }

  alert ( output_string );
}

Try it out by clicking on the Start link below:

Start

The break statement

We covered the break statement briefly in the section about the switch statement above. Generally speaking, break allows you to break out of the current switch, loop or label block and resume execution at the first statement after the block.

For example, here is our for loop snippet above, modified to break out of the loop once we've counted to 5:


function count_to_ten_with_break ( )
{
  var i;
  var output_string = "";

  for ( i=1; i<=10; i++ )
  {
    output_string += "I've counted to: " + i;
		
    if ( i == 5 )
    {
      break;
    }
  }

  alert ( output_string );
}

Try it out by clicking on the Start link below:

Start

You can also use break along with a label, to allow you to break out of several layers of loop nesting.

For example, this code contains two loops i and j, one inside the other. The outer loop i counts from 1 to 5, while the inner loop j counts from 5 to 1 backwards. However, once both i and j equal 3, we break out of both loops and jump to the label called end_loop:


function nested_count_with_break ( )
{
  var i,j;
  var output_string = "";


  end_loop:

  for ( i=1; i<=5; i++ )
  {
    for ( j=5; j>=1; j-- )
    {
      output_string += "i=" + i + ", j=" + j + "\n";

      if ( ( i == 3 ) && ( j == 3 ) )
      {
        break end_loop;
      }
    }
  }

  alert ( output_string );
}

Click on the Start link to try out this example:

Start

The continue statement

A continue statement can be placed within a while, do..while or for loop. Its purpose is to skip the rest of the code in the loop and jump to the next iteration of the loop.

For example, this code will count from 1 to 5, omitting the number 3, and display the results in an alert box:


function skip_three ( )
{
  var i, output_string;
  output_string = "";

  for ( i=1; i<=5; i++ )
  {
   	if ( i == 3 )
   	{
    		continue;
   	}

   	output_string += "I've counted to: " + i + "\n";
  }
	
  alert ( output_string );
}

Click on the Start link to try it out!

Start

You can also use continue with a label, as with the break statement above, in order to continue with a specified loop in a series of nested loops. The syntax is similar to that of the break statement:


continue label_name;

Conclusion

Being able to control program flow is an essential part of any programming langauge. Having read this tutorial, you are now familiar with the basic concepts of decision-making and looping in JavaScript, and you should now be well on your way to writing more advanced JavaScript applications.

Follow Elated

Related articles

Responses to this article

There are no repsonses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page