LOOPS/
R E CU R S I O N
J AVA S C R I P T
G R A D E – 1 1
2.
LOOPS
• A loopis a construct that repeats a set number of times, usually
based on a condition
Example :
You may want to output a number ten times. Instead of writing the
same line of code ten times, you can put it in a loop, which reduces
the amount of code.
You may not know how many times some code needs to be run. For
example, you want to multiply a number by itself until it is greater
than 1000.You will not know, at the start, how many times this code
needs to be run.
DO/WHILE
• In thisloop the condition is checked at the end of the loop, which means the loop will always
run at least once:
• Example 1:
var count = 0;
do
{
document.write (count * count);
count++;
}
while (count <=12);
In this example, 0*0 will always be output, the the value of count is checked and it decides
if the loop will run again.
5.
WHILE
• A whileloop runs the code while a condition.
• Example 1:
var count = 0;
while (count <=12)
{
document.write(count *count);
count++;
}
This loop will display 12 square numbers.
• Example 2:
var check = true;
while (check = true)
{
document.write(“It’s true”);
}
At the moment this loop will run infinitely.While
the variable check is true, it will continue to run.
6.
FOR
• In afor loop, you need to know the number of times the loop is to run.
• Example 1 :
The code below adds the value of total to itself ten times :
for (count = 0; count < 10; count++)
{
total = count;
document.write (total);
}
• Example 2 :
The for loop shown below will write the first 12 square numbers :
for (count = 1; count <=12; count++)
{
document.write(count*count);
}