JavaScript Statements - Looping
CSGNetwork FREE Source Code, Javascript Source, and Code Snippets!
CSGNetwork Custom Search
     Bookmark and Share
 
CSGNetwork
Snippets
Calculators
Top Free Apps
Home
Back



Right click this window and select "view source" in order to copy the source for this script.

JavaScript Statements - Looping

JavaScript Statements enable you to implement logic, looping, and more within your script.

Looping Statements

Statements Description
for Probably the common looping statement, "for" executes the enclosed statements any desired number of times.

Syntax:

for (initialValue; test; increment)
statement

Example:

for (x=0; x<3; x++)
document.write("This text is repeated three times<br>")

while A while loop continuously executes the enclosed statements as long as the tested expression evaluates to true. If the expression is false to begin with, the entire while loop is skipped.

Syntax:

while (expression)
statement

Example:

var number=0
while (number<5){
document.write(number+"<br>")
number++
}

do/while The do/while statement differs from the standard "while" in that the expression tested for is put at the end, ensuring that a do/while loop is always executed at least once..

Syntax:

do
statement
while (expression)

Example:

var number=0
do{
document.write(number+"<br>")
number++
}
while (number<5)

for/in For/in is a special looping statement that lets you display the property names (or properties' value) of an object.

Syntax:

for (variable in object)
statement

"variable" is any arbitrary variable that will hold the current property of the object in question as it is being looped. Here are two examples.

Example 1: This example writes out all the properties of the "navigator" object:

for (myprop in navigator)
document.write(myprop+"<br>")
 

Example 2: This example writes out the properties, plus their corresponding value, of the "navigator" object:

for (myprop in navigator)
document.write(myprop+": "+navigator[myprop]+"<br>")

 

break The break statement causes an exit of the innermost loop the statement is contained in. It's useful to prematurely end a loop:

Example:

for (i=0; i<6; i++){
if (puppies[i].name=="George")
alert("I found George!")
break
}

continue The continue statement causes JavaScript to skip the rest of the statements that may follow in a loop, and continue with the next iteration. The loop is not exited, unlike in a break statement.

Example:

for (i=1; i<6; i++){
if (i==4)
continue
document.write(i+"<br>")
}
//1, 2, 3, 5 is written out.



Bookmark and Share
Registered® Trademark™ and Copyright© 1973 - CSG, Computer Support Group, Inc. and CSGNetwork.Com All Rights Reserved