Section 3.3. Conditional Statements and Program Flow


3.3. Conditional Statements and Program Flow

Normally in JavaScript, the program flow is linear: each statement is processed in turn, one right after another. It takes deliberate action to change this. You can put the code in a function that is only called based on some action or event, or you can perform some form of conditional test and run a block of code only if the test evaluates to TRue.

One of the more common approaches to changing the program flow in JavaScript is through a conditional statement. As seen in the last few sections, the typical conditional statement has the following format:

if (value) { statements processed }

The term conditional comes from the fact that a condition has to be met before the block associated with the statement is processed. The example equates to: if some value (whether a result of an expression, a variable, or or a literal) evaluates to true, then do the following code; otherwise, jump to the end of the block, and continue processing at the very next line.

The use of the if keyword signals the beginning of the conditional test, and the parenthetical expression encapsulates the test. In the following code, the binary flag is tested against two bitmasks to see if either is matched. If so, and only then, the code contained in curly braces following the conditional expression is processed:

if ((fieldsSet & FIELD_A) && (fieldsSet & FIELD_C)) {    alert("Fields A and C are set"); }

The use of curly braces isn't necessary in this example because only one line of JavaScript is processed if the condition evaluates to TRue. If more than one JS statement needs to be processed, all the code must be contained within curly braces. These are commonly referred to as JavaScript blocks or blocks of code, and the curly braces let the script engine know that all of the JavaScript contained in the block is processed if the condition evaluates to true.

Since it's not unheard of that additional code is added at a later time, it's good practice to use curly braces around a statement processed through some flow-of-control event (such as a conditional statement).

JavaScript Best Practice: Use curly braces ({,}) around control blocksstatement(s) processed as a result of some flow-of-control action, such as a conditional statement.


To make the JavaScript more readable, it's also considered good form to indent the code that's contained within the curly braces. If the contained code has another conditional statement, the statements associated with it are indented the same amount, but from the original position and so on. Example 3-2 demonstrates three nested conditional statementseach with a block of code, each of which is indented. Change the variable's initial value to test the different conditional expressions.

Example 3-2. Three nested conditional statements, indented for easier reading

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Nested Indented Conditional statements</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ var prefChoice = 1; var stateChoice = 'OR'; var genderChoice = 'F'; if (prefChoice == 1) {    alert("You've picked option 1. Here is what will happen...");        if (stateChoice == 'OR') {       alert ("You've picked 1 and you're from Oregon.");       if (genderChoice == 'M') {          alert("You've picked 1 and you're from Oregon and you're a man.");       } // innermost block    } // middle block } // outerblock //]]> </script> </head> <body> <p>Imagine a form with five fields and a button here...</p> </body> </html>

Typically, code is indented three spaces with each block, and curly braces are lined up with the conditional statement. There's no fast rule on this; it doesn't impact the validity of the code.

In addition, the closing curly brace on each block is annotated with a comment. If the code is fairly long, complex, and full of nested blocks, such as those in Example 3-2, using comments to document the ending curly brace makes the code easier to read and maintain.

JavaScript Best Practice: In longer or more complex blocks of script, comment the ending brace to make it easier to identify exactly which block is being closed.


3.3.1. if...else

In many instances, a conditional test is performed, a block of one or more statements is processed, and the flow of the program continues at the end. However, not all logic can be expressed with just one test. Even within a spoken language, such as English, we have the concept of if...then...else to accommodate listing of various options:

If the sun is out, we'll go to the park; otherwise, we'll go to the movies.

In JavaScript, the use of the keyword else performs the same functionality: it provides for processing an alternative set of statements if the condition being tested evaluates to false:

if (expression) {    ... } else {    ... }

In the following code snippet, if the value in stateCode is "MA" for Massachusetts, the tax value is set to 3.5; otherwise, the tax is set to 4.5:

if (stateCode == "MA") {    taxPercentage = 3.5; } else {    taxPercentage = 4.5; }

Either the state code is "MA" or it's not; the tax percentage is set regardless.

However, not all conditions are either/or. In some instances, there might be more than one possible conditional outcome of interest, and you'll need to capture a sequence of tests: if then...else if then...else if then... and so on. This is managed in JavaScript through the addition of a conditional expression immediately following the else clause:

if (conditional expression) {    block of code } else if (other conditional expression) {    block of code }

These can be chained, one after the other, until all conditions have been tested.

In Example 3-3, the variable holding the state code is set in the code (purely for testing purposesnormally you don't know what the variable is). The three state codes are tested, and a different tax percentage is assigned if any of the three matches.

Example 3-3. Testing a value with multiple conditional statements

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>if...then...else...if</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ var stateCode = 'MO'; if (stateCode == 'OR') {    taxPercentage = 3.5; } else if (stateCode == 'CA') {    taxPercentage = 5.0; } else if (stateCode == 'MO') {    taxPercentage = 1.0; } else {    taxPercentage = 2.0; } alert(taxPercentage); //]]> </script> </head> <body> <p>Imagine a form with options to pick state code</p> </body> </html>

The program evaluates each expression in turn until it finds an expression that evaluates to true. At that point, the contained statements are processed, and the program continues on the first line after the complete conditional statement. If none of the expressions evaluates to TRue, the block of code following the else without a condition is processed, and the tax percentage is set accordingly.

You can continue adding additional else if statements testing the same variable, but after a time, the format is clumsy, hard to read, and inefficient. A better approach is to use the switch statement.

3.3.2. The switch Conditional Statement

The JavaScript switch statement is used when there are several possible outcomes resulting from a conditional expression. The JavaScript engine processes the expression and based on the result, one or more alternative options are processed:

switch (expression) {    case firstlabel:        statements;        [break;]    case secondlabel:       statements;        [break;]    ...    case lastlabel:       statements;       [break;]    default:       statements;

From the top, an expression that returns a value is given in the switch statement. case statements are then evaluated, in sequence from top to bottom, to see if any match. If a matching case is found, the statements contained within the particular case statement code block are processed. At this point, the program flow either continues processing each case statement, or the control of the program can be transferred to the first line following the end of the switch statement using the optional break.

If none of the cases match, the JavaScript engine looks for an optional default statement; if one is found, its code block is processed, and the program continues with the first line following the switch.

In the case where the same set of statements is processed for two or more case labels, the labels can be listed, with just the statements underneath:

case labelone: case labeltwo: case labelthree:    statements;    break;

With this technique, the statements are processed if any one of the three labelslabelone, labeltwo, or labelthreeare matched.

The switch statement is best explained with a demonstration. In Example 3-4, our state code is tested and if the value is OR, MA, or WI, the tax percentage is set to 3.5, and the state percentage to 0.5; if the code tested is MO, the tax percentage is set to 1.0, and the state percentage to 1.5; if the code tests out to CA, NY, and VT, the percentage is set to 4.5, and the state percentage to 2.6; if the code tests out to TX, the percentage is set to 3.0, with the state percentage left at 0.0; otherwise, the tax percentage is set to 2.0, with state set to 2.3.

Example 3-4. Using a switch statement to test expression against multiple values

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>switch statement</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ var stateCode = 'NY'; var statePercentage = 0.0; var taxPercentage = 0.0; switch (stateCode) {    case 'OR','MA','WI' :      statePercentage = 0.5;      taxPercentage = 3.5;      break;    case 'MO' :      taxPercentage = 1.0;      statePercentage = 1.5;      break;    case 'CA' :    case 'NY' :    case 'VT' :      statePercentage = 2.6;      taxPercentage = 4.5;      break;    case 'TX' :      taxPercentage = 3.0;      break;    default :      taxPercentage = 2.0;      statePercentage = 2.3; } alert("tax is " + taxPercentage + " and state is " + statePercentage); //]]> </script> </head> <body> <p>Imagine a form with options to pick state code</p> </body> </html>

From the top, the expression given in the switch statement is just the state code variable, stateCode. It can be any expression using any of the relational and logical operators (discussed in the next section). The case statements are then evaluated for a match. In the first, if the state code is OR, MA, or WI, the tax percentages are set to the same values. In this instance, the case values associated with the block are separated from the others by commas, which means any one of the three can match.

If the state code is TX or MO, the individual case blocks processed, but if the state code is CA, NY, or VT, the statements in the block associated with the last case, VT, are the ones processed. The other two state code cases have no statements of their own; neither do they have a break statement. This means, then, that if the state code is one of these, the program continues processing statements until the end of the switch statement, or until a break is reached. This is another approach that attaches the same statement block to more than one case value. It's identical in behavior to listing out the options, separated by a comma.

Finally if none of the cases match, the default is processed, and the program continues on the first statement after the switch.

Notice in the example that the only use of curly braces is around the switch control block itself. That's because with switch, program flow is controlled with the break statement, not curly braces. However, indentation still applies, thought it's not uncommon for the processed statements to be placed on the same line as the case condition:

case 'OR' : taxPercentage = 3.5; statePercentage = 2.0; break;

Most of the expressions being tested in the conditional control statements have been fairly simple equality tests. More complex conditional expressions, and even multiple expressions, can be used with conditional operators, discussed next.




Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net