asp.net.ph

Skip Navigation LinksHome > Abakada: Back to Basics > Basic Scripting > Programmimg With JavaScript

Programmimg With JavaScript

Abakada ~ Back to Basics


Controlling Program Flow

JavaScript supports a compact set of structures that are used to control program flow and incorporate interactivity in Web pages. This section provides an overview of these control structures.

Conditional Statements

A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else and switch.

if...else Statement

Use the if statement to perform certain statements if a logical condition is true; use the optional else clause to perform other statements if the condition is false. An if statement looks as follows:

if ( condition )
  {statements1}
else
  {statements2}

The condition can be any JavaScript expression that evaluates to true or false. The statements to be executed can be any JavaScript statements, including further nested if statements. If you want to use more than one statement after an if or else statement, you must enclose the statements in curly braces, {}.

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. For example:

var b = new Boolean ( false );
if ( b ) // this condition evaluates to true

In the following example, the function checkData returns true if the number of characters in a Text object is three; otherwise, it displays an alert and returns false.

function checkData ( ) {
if ( document.form1.threeChar.value.length==3 ) {
   return true
   }
else {
   alert ( "Enter exactly three characters. " +
   document.form1.threeChar.value + " is not valid." )
   return false
   }
}
switch Statement

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch statement looks as follows:

switch ( expression ) {
case label :
  statement;
  break;
case label :
  statement;
  break;
  ...
default :
  statement;
}

The program first looks for a label matching the value of expression and then executes the associated statement. If no matching label is found, the program looks for the optional default statement, and if found, executes the associated statement. If no default statement is found, the program continues execution at the statement following the end of switch.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

In the following example, if expr evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program terminates switch and executes the statement following switch. If break is omitted, the statement for case "Cherries" would also be executed.

switch ( expr ) {
case "Oranges" :
  document.write ( "Oranges are $0.59 a pound.<br>" );
  break;
case "Apples" :
  document.write ( "Apples are $0.32 a pound.<br>" );
  break;
case "Bananas" :
  document.write ( "Bananas are $0.48 a pound.<br>" );
  break;
case "Cherries" :
  document.write ( "Cherries are $3.00 a pound.<br>" );
  break; 
default :
  document.write ( "Sorry, we are out of "+ i +".<br>" ); 
}

document.write ( "Is there anything else you'd like?" );

Loop Statements

A loop is a set of commands that executes repeatedly until a specified condition is met. JavaScript supports the for, do while, while, and label loop statements ( label is not itself a looping statement, but is frequently used with these statements ). In addition, you can use the break and continue statements within loop statements.

Another statement, for...in, executes statements repeatedly but is used for object manipulation.

for Statement

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows:

for ( [ initial ]; [ condition ]; [ increment ] ) {
   statements
}

When a for loop executes, the following occurs:

  • The initial expression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
  • The condition expression is evaluated. If the value of condition is true, the statements execute. If the value of condition is false, the for loop cterminates.
  • The statements execute.
  • The update increment executes, and control returns to Step 2, where the condition is again evaluated.

The following function contains a for statement that counts the number of selected options in a scrolling list ( a Select object that allows multiple selections ). The for statement declares the variable i and initializes it to zero. It checks that i is less than the number of options in the Select object, performs the succeeding if statement, and increments i by one after each pass through the loop.

<head>
<script language="JavaScript">
<!--
function howMany ( chosen ) {
   var howMany = 0
   for ( var i=0; i < chosen.options.length; i ++ ) {
      if ( chosen.options [ i ].selected == true )
         howMany ++;
   }
   return howMany;
}
//--></script>
</head>

<body>
<center>
<form name="theForm">
   Choose some music types, then click the button:
   ...
   <select name="musicTypes" multiple>
      <option>Classical
      <option>Opera
      <option>Rythm and Blues
      <option>Rock
      <option>Jazz
      <option>Blues
      <option>New Wave
      <option>Punk
   </select>
...
<input type="Button" value="How many" 
   style="text-align:center" 
   onClick="alert ( 'Number of options selected: ' + 
      howMany ( document.theForm.musicTypes ) )">
</form>
</center>
</body>

 Show me 

do...while Statement

The do...while statement repeats until a specified condition evaluates to false. A do...while statement looks as follows:

do {
   statement
} while ( condition )

statement executes once before the condition is checked. If condition returns true, the statement executes again. At the end of every execution, the condition is checked. When the condition returns false, execution stops and control passes to the statement following do...while.

In the following example, the do loop iterates at least once and reiterates until i is no longer less than 5.

do {
   i+=1;
   document.write ( i );
} while ( i<5 );
while Statement

A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:

while ( condition ) {
   statements
}

If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop.

The condition test occurs before the statements in the loop are executed. If the condition returns true, the statements are executed and the condition is tested again. If the condition returns false, execution stops and control is passed to the statement following while.

The following while loop iterates as long as n is less than three:

n = 0
x = 0
while ( n < 3 ) {
   n ++
   x += n
}

With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:

  • After the first pass: n = 1 and x = 1
  • After the second pass: n = 2 and x = 3
  • After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Infinite loop. Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate. The statements in the following while loop execute forever because the condition never becomes false:

while ( true ) {
   alert ( "Hello, world" ) }
label Statement

A label provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.

The syntax of the label statement looks like the following:

label : 
   statement

The value of label may be any JavaScript identifier that is not a reserved word. The statement that you identify with a label may be any type.

In this example, the label markLoop identifies a while loop.

markLoop:
while ( theMark==true )
   doSomething ( );
}
break Statement

Use the break statement to terminate a loop, switch, or label statement.

  • When you use break with a while, do-while, for, or switch statement, break terminates the innermost enclosing loop or switch immediately and transfers control to the following statement.
  • When you use break within an enclosing label statement, it terminates the statement and transfers control to the following statement. If you specify a label when you issue the break, the break statement terminates the specified statement.

The syntax of the break statement looks like the following:

1. break
2. break [ label ] 

The first form of the syntax terminates the innermost enclosing loop, switch, or label; the second form of the syntax terminates the specified enclosing label statement.

The following example iterates through the elements in an array until it finds the index of an element whose value is theValue:

for ( i = 0; i < a.length; i++ ) {
   if ( a [ i ] = theValue );
      break;
}
continue Statement

The continue statement can be used to restart a while, do-while, for, or label statement.

  • In a while or for statement, continue terminates the current loop and continues execution of the loop with the next iteration. In contrast to the break statement, continue does not terminate the execution of the loop entirely. In a while loop, it jumps back to the condition. In a for loop, it jumps to the increment-expression.
  • In a label statement, continue is followed by a label that identifies a label statement. This type of continue restarts a label statement or continues execution of a labelled loop with the next iteration. continue must be in a looping statement identified by the label used by continue.

The syntax of the continue statement looks like the following:

1. continue
2. continue [ label ] 

The following example shows a while loop with a continue statement that executes when the value of i is three. Thus, n takes on the values one, three, seven, and twelve.

i = 0
n = 0
while ( i < 5 ) {
   i++
   if ( i==3 )
      continue
   n += i
}

A statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program terminates the current iteration of checkj and begins the next iteration. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is completed, and checkiandj reiterates until its condition returns false. When false is returned, the program continues at the statement following checkiandj.

If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement.

checkiandj : 
   while ( i<4 ) {
      document.write ( i + "<br>" ); 
      i+=1; 
      checkj : 
         while ( j>4 ) {
            document.write ( j + "<br>" ); 
            j-=1; 
            if ( ( j%2 ) ==0 );
            continue checkj;
            document.write ( j + " is odd.<br>" );
         }
      document.write ( "i = " + i + "<br>" );
      document.write ( "j = " + j + "<br>" );  
   }

Some relevant references:

 

Previous: JavaScript Basics Next: Data Entry Validation

Back to top


© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note