conditionals statements:

What is a Loop?

A loop will allow you to execute a block of code a specified number of times. This is based on a limit that you may set or a condition.

A loop prevent us from writing the same line of code over and over again.

For example: To write "hello world" to a document10 times I would hve to type document.write("hello world") ten times like so:

document.write ("hello world");
document.write ("hello world");
document.write ("hello world");
document.write ("hello world");
document.write ("hello world");
document.write ("hello world");
document.write ("hello world");
document.write ("hello world");
document.write ("hello world");
document.write ("hello world");

This is can lead to redundant code. Just image that it is was neccessary to write this 1000 times. Now the picture should be quit clear as to why loops are neccessary. Loop can short code tremendously by providing a starting point alsong with a condition to stop or a set number of time to loop.

There are 3 types of loops.

For loop - The For loop is used to execute the same block of code a specified number of times

While loop - Use the While loops to execute the same block of code while or until a condition is true

Do while loop - The Do While loop should be used to execute the same block of code while or until a condition is true as well. The difference from the while loop is that this loop will always be executed once, even if the condition is false, because the statements are executed before the condition is tested

For Loop Syntax

Do this block 10 times

for (varnam=1;varname<=10; varname+=1)

{

{

document.write (" hello World")

document.write ("hello world");

}

}

Declare & Assign varname 1

Test Loop Condition (is varnam, less than or = to 10)

increment the varname variable by one.

varnam=1

varname<=10

varname+=1


For Loop Example

Source: for loop

Results :

for (count=1;count<5;count += 1)
{
document.write(count+" pass <br>");
}

 

Source: while loop

Results :

var count=1;
while (count<5)
{
document.write(count+" pass <br>");
count += 1;
}

A do while will execute at least once since the condition is at the end of the loop

Source:

Results :

var count=;
do
{
document.write(count+" pass <br>");
count += 1;
} while (count<5);

 

Source: Reserve word do while

Results :

var count=1;
do
{
if ((count>2)&&(count<6)||(count==10))
{
document.write(count+" is a cool number <br>");
}
else
{
document.write(count+" is not a cool number <br>");
}
count += 1;
}while (count<=10);

 
Imsg
Discussion

Blogging

E-mail

 

JAVASCRIPT    -    LESSON 3
J s - l o o p s