Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | if…else Selection Statement - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Control Statements I

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

if…else Selection Statement - JavaScript(JS)

The if selection statement performs an indicated action only when the condition evalu-ates to true; otherwise, the action is skipped.

ifelse Selection Statement

 

The if selection statement performs an indicated action only when the condition evalu-ates to true; otherwise, the action is skipped. The ifelse selection statement allows the programmer to specify that a different action is to be performed when the condition is true than when the condition is false. For example, the pseudocode statement

 

If student’s grade is greater than or equal to 60

Print “Passed”

Else

Print “Failed”

 

prints Passed if the student’s grade is greater than or equal to 60 and prints Failed if the student’s grade is less than 60. In either case, after printing occurs, the next pseudocode statement in sequence (i.e., the next statement after the whole ifelse structure) is per-formed. Note that the body of the Else part of the structure is also indented.

The indentation convention you choose should be applied carefully throughout your programs (both in pseudocode and in JavaScript). It is difficult to read programs that do not use uniform spacing conventions.

 

The preceding pseudocode If…Else statement may be written in JavaScript as

 

if       ( studentGrade >= 60 ) document.writeln( "Passed" );

 

else

 

document.writeln( "Failed" );

 

The flowchart shown in Fig. 7.4 illustrates the ifelse selection statement’s flow of con-trol. Once again, note that the only symbols in the flowchart (besides small circles and ar-rows) are rectangles (for actions) and a diamond (for a decision). We continue to emphasize this action/decision model of computing. Imagine again a deep bin containing as many empty double-selection structures as might be needed to build a JavaScript algo-rithm. The programmer’s job is to assemble the selection structures (by stacking and nest-ing) with other control structures required by the algorithm and to fill in the empty rectangles and empty diamonds with actions and decisions appropriate to the algorithm’s implementation.

 

JavaScript provides an operator, called the conditional operator (?:), that is closely related to the ifelse statement. The operator ?: is JavaScript’s only ternary operator— it takes three operands. The operands together with the ?: form a conditional expression. The first operand is a boolean expression, the second is the value for the conditional expression if the expression evaluates to true and the third is the value for the conditional expression if the expression evaluates to false. For example, consider the following state-ment

 

document.writeln( studentGrade >= 60 ? "Passed" : "Failed" );

 

 


contains a conditional expression that evaluates to the string "Passed" if the condition studentGrade >= 60 is true and evaluates to the string "Failed" if the condition is false. Thus, this statement with the conditional operator performs essentially the same operation as the preceding ifelse statement. The precedence of the conditional operator is low, so the entire conditional expression is normally placed in parentheses to ensure that it eval-uates correctly.

 

Nested ifelse statements test for multiple cases by placing ifelse statements inside ifelse statements. For example, the following pseudocode statement indicates that the program should print A for exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other grades:

 

If student’s grade is greater than or equal to 90

Print “A”

Else

If student’s grade is greater than or equal to 80

Print “B”

Else

If student’s grade is greater than or equal to 70

Print “C”

Else

If student’s grade is greater than or equal to 60

Print “D”

Else

Print “F”

 

This pseudocode may be written in JavaScript as

 

if       ( studentGrade >= 90 ) document.writeln( "A" );

 

else

 

if ( studentGrade >= 80 ) document.writeln( "B" );

 

else

 

if ( studentGrade >= 70 ) document.writeln( "C" );

 

else

 

if ( studentGrade >= 60 ) document.writeln( "D" );

 

else

 

document.writeln( "F" );

 

If studentGrade is greater than or equal to 90, all four conditions will be true, but only the document.writeln statement after the first test will execute. After that particular doc-ument.writeln executes, the else part of the outer ifelse statements is skipped.

Most JavaScript programmers prefer to write the preceding if structure as

 

if       ( grade >= 90 ) document.writeln( "A" );

 

else if ( grade >= 80 ) document.writeln( "B" );

 

else if ( grade >= 70 ) document.writeln( "C" );

 

else if ( grade >= 60 ) document.writeln( "D" );

 

else

 

document.writeln( "F" );

 

The two forms are equivalent. The latter form is popular because it avoids the deep inden-tation of the code to the right. Such deep indentation often leaves little room on a line, forcing lines to be split and decreasing program readability.

 

It is important to note that the JavaScript interpreter always associates an else with the previous if, unless told to do otherwise by the placement of braces ({}). This situation is referred to as the dangling-else problem. For example,

 

if ( x > 5 )

 

if ( y > 5 )

 

document.writeln( "x and y are > 5" );

 

else

 

document.writeln( "x is <= 5" );

 

appears to indicate with its indentation that if x is greater than 5, the if structure in its body determines whether y is also greater than 5. If so, the body of the nested if structure outputs the string "x and y are > 5". Otherwise, it appears that if x is not greater than 5, the else part of the ifelse structure outputs the string "x is <= 5".

 

Beware! The preceding nested if statement does not execute as it appears. The inter-preter actually interprets the preceding statement as

 

if ( x > 5 )

 

if ( y > 5 )

 

document.writeln( "x and y are > 5" ); else

 

document.writeln( "x is <= 5" );

 

in which the body of the first if statement is a nested ifelse statement. This statement tests whether x is greater than 5. If so, execution continues by testing whether y is also greater than 5. If the second condition is true, the proper string—"x and y are > 5"—is displayed. However, if the second condition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5.

 

To force the preceding nested if statement to execute as it was intended originally, it must be written as follows:

 

if ( x > 5 )

 

{

 

if ( y > 5 )

 

document.writeln( "x and y are > 5" );

 

}

 

else

 

document.writeln( "x is <= 5" );

The braces ({}) indicate to the interpreter that the second if statement is in the body of the first if statement and that the else is matched with the first if statement. In Exercises 7.21 and 7.22, you will investigate the dangling-else problem further.

 

The if selection statement expects only one statement in its body. To include several statements in an if statement’s body, enclose the statements in braces ({ and }). This can also be done in the else section of an ifelse statement. A set of statements contained within a pair of braces is called a block.

The following example includes a block in the else part of an ifelse statement:

 

if       ( grade >= 60 ) document.writeln( "Passed" );

 

else

 

{

 

document.writeln( "Failed<br />" );

 

document.writeln( "You must take this course again." );

 

}

 

In this case, if grade is less than 60, the program executes both statements in the body of the else and prints

 

Failed.

 

You must take this course again.

 

Note the braces surrounding the two statements in the else clause. These braces are im-portant. Without them, the statement

 

document.writeln( "You must take this course again." );

 

would be outside the body of the else part of the if and would execute regardless of whether the grade is less than 60.

Syntax errors (e.g., when one brace in a block is left out of the program) are caught by the interpreter when it attempts to interpret the code containing the syntax error. A logic error (e.g., the one caused when both braces around a block are left out of the pro-gram) also has its effect at execution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing, but the program produces incorrect results.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.