Looping and conditionals
Looping means that the same line of code is repeated. Conditionals means that you can have a line of code where a variable has a condition of whether it is true.
Looping and conditionals are a part of language constructs. For
example,
var i;
for (i = 0; i < 10; i++)
{
out.writeln(i + ": hello world");
}
The
line for (i = 0; i < 10; i++)
is an example of looping. When looping, you need
to ensure that a condition tells the loop when to end. For
example,var i = 1;
while ( i < 10)
{
out.writeln(i + "");
if (i == 3)
{
out.writeln("breaking");
break;
}
i++;
}
out.writeln("i at loop completion is: " + i );
The
prior script uses a break to exit the loop. To continue a loop after a break and go back to the
beginning of the loop for the next iteration,
type:var i = 1;
while ( i < 10)
{
i++;
if (i == 3)
{
out.writeln("continuing (not printing i)");
continue;
}
out.writeln(i + "");
}
Another conditional language construct is the "else" statement.
If something is conditional, you need to decide whether you want to run
the next object. The "else" stands for otherwise, meaning, if you
are hungry you eat dinner, otherwise you watch television. If you do
not have the "else" in the code, the script would mean, you eat dinner
and then watch television. The example script of an if else statement:
var hungry = true;
if (hungry)
{
out.writeln("Where's dinner?");
}
else
{
out.writeln("not hungry now!");
}