reptile7's JavaScript blog
Thursday, June 08, 2006
 
Taking JavaScript Mountain, By Strategy
Blog Entry #41

We continue today our introductory treatment of JavaScript looping techniques. Having discussed for loops in our last episode, we turn our attention in this entry to while loops, the focus of HTML Goodies' JavaScript Primers #25. In "The Concept[s]" of Primers #24 and #25, Joe informs us, "In general, you use For loops when you know how many times you want to perform a loop. Use While loops when you are not sure how many times you want to perform a loop." Somewhat more formally, using Wikipedia's 'taxonomy,' we can classify a for loop as a count-controlled loop and a while loop as a condition-controlled loop. Joe then proceeds to use a while loop in the Primer #25 Script in a count-controlled manner; in fairness to Joe, however, Netscape, DevGuru, and JavaScript Kit all do the same with their respective while loop examples. Ultimately, there is indeed much more similarity than difference between for loops and while loops.

Like for loops, while loops are not unique to JavaScript, but also appear in other programming languages. The syntax of a JavaScript while loop is given below:

while (condition) {
// as long as the condition is true, execute the following code repeatedly
command_statement_A;
command_statement_B; etc. }
// the braces are optional if there's just one command statement

After the while keyword is a set of parentheses containing a Boolean condition that is evaluated at the beginning of each iteration of the loop; if the condition is true, then the subsequent loop code in braces executes repeatedly, as noted above, but if and when the condition becomes false, then the loop stops.

Unlike the parenthesized expressions of a for loop, the while condition is not optional. Consider the following for loop, which faithfully reproduces the effect of the Primer #24 Script:

<script type="text/javascript">
var i = 1;
for ( ; ; ) {
if (i == 6) break
document.write(i + "<br>");
i=i+1; }
</script>

If you were to replace for ( ; ; ) with while ( ), then you'd get a syntax error.

Let's turn now to the Primer #25 Script:

<html><head></head><body>
<script type="text/javascript">
loops=3;
num=1;
while (num <= loops) {
document.write("Happy ");
num=num+1; }
document.write("Birthday");
</script></body></html>

The script's while statement, as noted previously, is a count-controlled loop. We've got an initial-expression, num=1, a condition, num <= loops, and an increment-expression, num=num+1, so we can wave our magic wand and - Poof! - easily turn the while loop into a for loop, if desired:

loops=3;
for (num=1; num <= loops; num=num+1) {
document.write("Happy "); }
document.write("Birthday");

For a count-controlled while loop, the placement of expressions is important: the initial-expression is necessarily placed before the while statement, whereas the increment-expression is necessarily placed inside the while loop {body}. Other than that, I don't have anything to add to Joe's script deconstruction.

The do...while statement

As detailed above, a while statement (1) initially evaluates its condition and (2) then executes or doesn't execute its command statements. JavaScript also has a related do...while looping statement that reverses this order of operations, ensuring that the loop {body} is executed at least once, according to the following syntax:

do {
command_statement_A;
command_statement_B; etc. }
while (condition)

The browser executes the do commands in the first (and possibly last) iteration of the loop, and then the while condition is evaluated; subsequently, the do commands are re-executed, and repeatedly so, if and as long as the while condition is true, but are not re-executed if the while condition is false.

In illustration, consider the while loop that appears in the random-number-guessing-game guessnum3( ) function in the "Other code possibilities" section of Blog Entry #38:

function guessnum3( ) {
now=new Date( ); num=(now.getSeconds( ))%10; num=num+1;
guess=prompt("Your guess?");
if (guess == num) {alert("YOU GUESSED IT!!");}
while (guess != num) {
alert("No. Try again.");
guess=prompt("Your guess?");
if (guess == num) {alert("YOU GUESSED IT!!");} } }

At last, a bona fide condition-controlled while loop! And with respect to the present discussion, a while loop that is more efficiently formulated as a do...while loop, which in this case allows the elimination of duplicate prompt( ) commands and if statements:

function guessnum3a( ) {
now=new Date( ); num=(now.getSeconds( ))%10; num=num+1;
do {
guess=prompt("Your guess?");
if (guess == num) alert("YOU GUESSED IT!!");
else alert("No. Try again."); }
while (guess != num) }

Try it out:


The Primer #25 Assignment

In the Primer #25 Assignment, Joe asks the reader to add some user interactivity to the Primer #25 Script, specifically, to modify the script so that, in lieu of presetting a three-iteration loop with the loops=3 statement, the user is able to customize the number of while iterations, and thus the number of "Happy "s written to the page, via a number entered into a prompt( ) box.

We noted in Blog Entry #37 that prompt( ) outputs are strings, and Joe's assignment answer duly makes use of the eval( ) function to convert tellme, the identifier to which his prompt("How many Happy's do you want before the word Birthday?") command is assigned, to a number. For the first time (this being the third time we've seen the eval( ) function), Joe comments in the assignment on the purpose of eval( ): "Remember to use Eval( ) to change the [prompt( )] response from text to a number." And eval( ) finally makes an appearance on the end-of-primer "Click Here For What You've Learned" page (although its definition there is seriously incomplete). Better late than never!

However, as in the Primer #22 Script, the use of the eval( ) function in the Primer #25 Assignment answer is in fact unnecessary. With the exception of the === (strict equal) and !== (strict not equal) operators, all of JavaScript's comparison operators compare their operands without regard to data type, with the browser reconciling different data types as necessary. We can thus rewrite the assignment answer script as:

<script type="text/javascript">
tellme=prompt("How many 'Happy's do you want before the word Birthday?");
num=1;
while (num <= tellme) {
document.write("Happy ");
num=num+1; }
document.write("Birthday");
</script>

Again, tellme will be converted to a number when the while condition is evaluated, obviating the need for a loops=eval(tellme) statement.

We'll see new things and old in Primer #26, which we'll cover in the next post; most importantly, we'll introduce the built-in JavaScript Array object, and we'll also look at another guessing-game script that features if...else and while statements.

reptile7

Comments: Post a Comment

<< Home

Powered by Blogger

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