Flylib.com

Books Software

 
 
 

Creating while Loop Statements

Creating while Loop Statements

There are other loops besides the for loop in JavaScript, such as the while loop. The while loop tests a condition each time the loop is executed. If the condition is true, it executes the code in the loop. Here's what this loop looks like in outline:

while (

condition

){

code

}

For example, here's how you write the example we used in the discussion of for loops as a while loop:

Listing ch06_09.html
<HTML>
     <HEAD>
        <TITLE>
            Using the while Statement
        </TITLE>
    </HEAD>

    <BODY>
        <CENTER>
            <H1>
                Using the while Statement
            </H1>
        </CENTER>

        <SCRIPT LANGUAGE = "JavaScript">

var loopIndex = 0


while(loopIndex < 10){


loopIndex++


document.writeln("The loop index value is " +


loopIndex + "<BR>")


}

</SCRIPT>
    </BODY>
</HTML>

You can see the results of this code in Figure 6-9.

Figure 6-9. Using a JavaScript while loop in Internet Explorer.

graphics/06fig09.gif

Creating do while Loops

There's another form of the while loop available: the do...while loop. This loop is much like the while loop, except that it checks the loop condition at the end, after the code in the loop has been executed, not at the beginning. Here's what this loop looks like in outline:

do {

code

} while (condition)

Actually, there's a big difference between the while and do...while loops in programmatic terms: The code in a do...while loop is always executed at least once, although that's not true of a while loop. Take a look at this example:

var number = 25 
do {
    document.writeln("The reciprocal of "
    + number + " is "
    + 1/number + "<BR>")
    --number
} while (number > 0)

Here I'm displaying a sequence of reciprocal values, from 1/25 up to 1/1 , using a do...while loop. However, this would be a problem if number were initialized to because the first reciprocal that the code would attempt to calculate is 1/0 :


var number = 0

do {
    document.writeln("The reciprocal of "
    + number + " is "
    + 1/number + "<BR>")
    --number
} while (number > 0)

A better choice is to use the while loop here: It checks the value in number first and won't attempt to calculate a reciprocal if that value equals :

var number = 25

while (number > 0) {

document.writeln("The reciprocal of "
    + number + " is "
    + 1/number + "<BR>")
    --number
}

Both forms of the while loop have their places, however. For example, if you need to execute the body of the loop before testing to see if the loop should continue, use the do...while loop.

Creating Functions in JavaScript

Functions are a crucial part of JavaScript programming. With a function, you can wrap some code into a programming construct, a function, and you then call that function to execute that code.

You create functions with the function statement. Here's how that statement looks in outline:

function functionname([argument1 [, argument2 [, ...argumentn]]]) 
{

code

}

In this case, I'm passing the values argument1 , argument2 , and so on to this function. The code in the function has access to these values. A function can also return a value; to do that, you use the return statement.

Here's an example. In this case, I'm creating a function named getTime , which will return the current time. Notice the syntax of the function statement hereI'm adding an empty set of parentheses after the name of the function. Those parentheses are always necessary; when we pass values to a function, they'll be listed in the parentheses. The getTime function doesn't accept any passed values, so the parentheses are empty:

function getTime() 
{
    var now = new Date
    var returnValue = now.getHours() + ":"
    + now.getMinutes()
    return(returnValue)
}

In this case, we're using the JavaScript Date class and creating a new object of that class named now using the new operator. I can use the getHours and getMinutes methods of this new object (these methods are built into the Date class) to get the current time.

In fact, methods are just functions built into objects. If you continue on in JavaScript to creating your own classes and objects, the functions you add to a class will be called methods.

In this example, I place the current time into a string named returnValue . That string is what I return from the function, using the return statement. After creating this function, you're free to use it in your code. Here's how I place that function in a <SCRIPT> element. Note that the code in functions is not run automatically when the page loads; it's run only when the function is actually called:

Listing ch06_10.html
<HTML>
    <HEAD>
        <TITLE>
            Using JavaScript Functions
        </TITLE>
    </HEAD>

    <BODY>
        <CENTER>
            <H1>
                Using JavaScript Functions
            </H1>
        </CENTER>

        <SCRIPT LANGUAGE = "JavaScript">
            document.writeln("The time is " + getTime()
            + " right now.")

            function getTime()
            {
                var now = new Date
                var returnValue = now.getHours() + ":"
                + now.getMinutes()
                return(returnValue)
            }
        </SCRIPT>
    </BODY>
</HTML>

You can see this page in Internet Explorer in Figure 6-10. As you can see there, things have worked out as we expected. When the page is loaded, the document.writeln statement is executed, which means that the call to the getTime function is also executed. The getTime function returns the current time as a string, which is incorporated into the text that's displayed in the page.

Figure 6-10. Using a JavaScript function in Internet Explorer.

graphics/06fig10.gif

We've seen how to write a function that returns a value now, but what about passing values to functions so they can work on them? I'll take a look at how that works next .