The JavaScript Diaries: Part 5 - Page 7
[previous] [next]
The JavaScript Diaries: Part 5
Nested Loops
You can also nest for
statements to obtain greater control and add a variety of tasks. Try this one and see what happens.
for (var jsNot=0;jsNot<10;jsNot++) { document.write("JavaScript is not Java!<br>"); for (jsNot2=1;jsNot2<2;jsNot2++) { document.write("Are you getting this?<br>"); } }
It's a little tedious but you get the picture. Let's take a look at what is happening here:
|
You can also nest other types of blocks. Let's take a previous script and
add an if
nesting loop to it:
for (var newNum=1; newNum<4; newNum++) { document.write("This pass is #" + newNum + "<br>"); if (newNum==3) { document.write("That's all she wrote folks!"); } }
In this loop, when the variable newNum
equals 3, which would be on its last loop, an if
statement is executed. Let's try another one that's a little more complex:
for (var jsNot=0;jsNot<10;jsNot++) { if (jsNot==4) { document.write("Are you getting this?<br>"); } else if (jsNot==9) { document.write("I think you got the point!"); } else { document.write("JavaScript is not Java!<br>"); } }
The continue
and break
Commands
You can also control loops using the continue
and break
commands. These allow you to skip a certain part of the loop, or stop it altogether,
if a condition is met. Look at the following script:
for (var newNum=1; newNum<9; newNum++) { if (newNum==5) { continue; } document.write("This pass is #" + newNum + "<br>"); }
|
A break
command acts a little differently in that it actually
stops the loop from executing any additional code within the loop:
for (var newNum=1; newNum<9; newNum++) { if (newNum==5) { break; } document.write("This pass is #" + newNum + "<br>"); }
In this loop, if the variable newNum
is equal to 5, the loop will stop execution completely.
I'm sure you can see how this could be beneficial in many cases. Try them yourself and see what happens.
Nesting loops add another dimension to your programming skills that aid you in creating more effective scripts. Don't be afraid to use them.
[previous] [next]
Created: June 10, 2005
URL: