reptile7's JavaScript blog
Friday, April 28, 2006
 
More on If...else Statements
Blog Entry #37

(In the text of today's entry, we continue our adventures in syntactical color-coding: all references to if...else statements appear in green, whereas all references to variable identifiers appear in red as they did in the previous post.)

HTML Goodies' JavaScript Primers #13 and Blog Entry #28 introduced us to if...else statements in the context of a discussion of the confirm( ) method of the window object. To my observation, the confirm( ) method does not crop up all that often in JavaScript scripts, but as for if...else statements, well, that's another story - you see these statements used just about everywhere in the JavaScript world, and for good reason. If...else statements add considerable flexibility to a script, transforming it from a mere sequence of commands into a 'contingency plan' that allows the scriptwriter to map out two or more courses of action for a given situation. We return to if...else statements in this and the next two posts, as Primers #21, #22, and #23 compose an if...else 'primer trilogy' of sorts, presenting a series of scripts that do simple-yet-fun things courtesy of if...else statements.

Primer #21, "Introduction to IF and Branching," appropriately kicks off our if...else festival; its focal script, which engages the user in a 'conversation' on sports, appears below:

<html><head>
<script type="text/javascript">
function askuser( ) {
var answer="   "; // function command #1
var statement="Answer yes or no"; // function command #2
var answer=prompt("Do you like sports?"); // function command #3
if (answer == "yes") // if statement #1
{statement="I like sports too!";}
if (answer == "no") // if statement #2
{statement="I hate sports too!";}
alert(statement); } // function command #4
</script></head>
<body>
<h1>Activities</h1>
<form action="">
<input type="button" value="click me" onClick="askuser( );">
</form></body></html>

The if...else action occurs in the askuser( ) function in the document head. Note that the script does not have an else part, which Joe circumvents by a careful ordering of commands; recall from Blog Entry #28 that the else part of an if...else statement is in fact optional. However, we'll see below that the script can have an else part if desired.

Let's begin our deconstruction with askuser( )'s function command #3, which pops up a prompt( ) box asking the age-old question, "Do you like sports?" The user types in a response, which is assigned to the variable answer after the "OK" button is clicked. The script is set up to handle three possibilities:

(1) If the user types in "yes" - all in lowercase letters - then if statement #1 kicks in:

if (answer == "yes") {statement="I like sports too!";}

The conditional expression in parentheses, answer == "yes", utilizes the == equal comparison operator. In effect, if statement #1 says, "Is it true that the value of answer is equal to "yes"? If this condition is met [as it is in this case], then assign the text string "I like sports too!" to the variable statement." Subsequently, function command #4 displays statement on an alert( ) box.

Recall from Blog Entry #30 that in JavaScript a single equals sign (=) is an assignment operator that actively assigns the value of its right operand to its left operand. With respect to if statement #1's condition, we're not assigning anything, specifically, we're not assigning "yes" to answer, whose value is set by the prompt( ) command; rather, we are comparing answer and "yes" to see if they are equal, with the == operator returning true if they are and false if they aren't. So, in summary and at the risk of belaboring the obvious, assignment and comparison are two different operations requiring two different operators. Netscape's if...else documentation, linked above, notes that it's possible to have (x = y) assignment statements in if conditional expressions, but that such situations are the exception and not the rule.

(2) If the user answers "no", again all in lowercase letters, then if statement #1's condition returns false, so the browser skips over {statement="I like sports too!";} and moves on to if statement #2:

if (answer == "no") {statement="I hate sports too!";}

If statement #2's condition now returns true, so "I hate sports too!" is assigned to statement, which is again via function command #4 displayed on an alert( ) box. Analogously, the browser skips over {statement="I hate sports too!";} when the user answers "yes", because in this case if statement #2's condition returns false.

(3) For all other responses - including leaving the prompt( ) input field blank and/or clicking the "Cancel" button - the value of statement is set near the beginning of the script by function command #2:

var statement="Answer yes or no";

If the user answers "yes" (if statement #1's condition is true), then {statement="I like sports too!";} overwrites function command #2, and you see "I like sports too!" on the alert( ) box; similarly, if the user answers "no" (if statement #2's condition is true), then {statement="I hate sports too!";} overwrites function command #2, and you see "I hate sports too!" on the alert( ) box. For all other answers ("empty" or otherwise), the conditions of if statements #1 and #2 are both false, and you see "Answer yes or no" on the alert( ) box. Very logical.

As should be clear, the code sequence is important here; had Joe placed the var statement="Answer yes or no" catch-all after if statement #2 (i.e., just before function command #4), then var statement="Answer yes or no" would overwrite {statement="I like sports too!";} or {statement="I hate sports too!";} for the answers "yes" or "no", respectively, and you'd see "Answer yes or no" on the alert( ) box in all cases.

Before moving on, a quick comment on function command #1: somewhat mystifyingly, Joe begins the askuser( ) function by assigning three blank spaces to the answer variable in its initial declaration; "[t]hat empty space will be filled with what the user enters into the prompt box," Joe tells us in the "Deconstructing the Script" section of the primer. Perhaps you are thinking to yourself, "I'll bet we can delete function command #1 without any problems; the prompt( ) command is going to overwrite those spaces anyway," and you would be correct*. Note that the Primer #21 Assignment's answer script, which is patterned on the Primer #21 Script, does not contain a corresponding answer declaration prior to the prompt( ) command.

(*I myself was wondering if Joe wanted to ensure that answer is interpreted as a string data type - I was reminded of his <SCRIPT>document.write("" +name+ "")</SCRIPT> code in the answer to the Primer #6 Assignment. BTW, I find on my computer that a y=prompt(x,y) output y is indeed interpreted as a string regardless of what I enter (including numbers) into the prompt( ) box.)

Else possibilities

When I first read through Primer #21, I thought, "Why don't we put the 'Answer yes or no' catch-all at the end of the function in an else block of code?" I.e.:

function askuser2( ) {
var answer=prompt("Do you like sports?");
if (answer == "yes") {statement="I like sports too!";} // if statement #1
if (answer == "no") {statement="I hate sports too!";} // if statement #2
else
{statement="Answer yes or no";}
window.alert(statement); }

In practice, the function above, as written, works OK for the "no" and for the anything-but-"yes"-or-"no" answers, but not for the "yes" answer, which gives "Answer yes or no" on the alert( ) box. Evidently, for an if...if...else statement, if if statement #2's condition is false, then the else command(s) will execute, even if if statement #1's condition is true. However, we can easily get around this problem by rolling if statements #1 and #2 into an encompassing if statement as follows:

function askuser3( ) {
var answer=prompt("Do you like sports?");
if ((answer == "yes") || (answer == "no")) // if statement #0
{
if (answer == "yes") {statement="I like sports too!";} // if statement #1
if (answer == "no") {statement="I hate sports too!";} // if statement #2
}
else {var statement="Answer yes or no.";}
alert(statement); }

In the code above, if statements #1 and #2 are nested in the outer if statement #0, whose condition, ((answer == "yes") || (answer == "no")), features the double-vertical bar (||) logical/Boolean OR operator, which returns true if either of its operands, (answer == "yes") and (answer == "no") in this case, are true, and which returns false if both of its operands are false. The askuser3( ) function faithfully duplicates the effect of the Primer #21 Script for all possible answers; it's a bit more complicated than the askuser( ) function but reads more straightforwardly, IMO.

Answer case-sensitivity

At the end of his deconstruction, Joe emphasizes, "Remember that JavaScript is case-sensitive. Thus if you type YES or Yes, the condition will be false! You must type yes for the condition to be true." His proposed workaround: "You can fix this by adding more and more IF statements covering all caps or capitalized answers." Yeah, I suppose we could do that, but a much more elegant solution is at hand, namely, we can use the toLowerCase( ) method of the String object to convert uppercased yeas and nays to "yes" and "no", respectively. All we need to do is to follow the var answer=prompt("Do you like sports?") command (in either the askuser( ) function or the askuser3( ) function) with:

answer = answer.toLowerCase( );

and our case-sensitivity problems are solved, with one glitch: clicking the "Cancel" button on the prompt( ) box in this case throws an error (MSIE: "'null' is not an object"; Netscape: "answer has no properties"). (Recall from Blog Entry #11 that canceling a prompt( ) box outputs the null value.) However, after a bit of experimentation, I was able to eliminate this complication with the following code:

function askuser4( ) {
var statement="Answer yes or no.";
var answer=prompt("Do you like sports?");
if (answer == null)
{alert(statement);}
else
{answer = answer.toLowerCase( );
if (answer == "yes") {statement="I like sports too!";}
if (answer == "no") {statement="I hate sports too!";}
alert(statement); } }

Try it out:

In our next episode, we'll take on Primer #22, which uses an if...else statement in a guessing game script.

reptile7

Comments: Post a Comment

<< Home

Powered by Blogger

Actually, reptile7's JavaScript blog is powered by Café La Llave. ;-)