JS loops :
Loop statements are used to repeat the execution of a set of statements. There are three loop statements available in JavaScript.
1. do... while Statement
2.while statement
3.for statement
do ...while statement
do ... while executes the statements for once even if the condition is wrong because the condition is checked only at the end of the loop .
In above example at the time of onLoad event happens, it will call that color ( ) function.
In color function an input is obtained from the user using the prompt method of window object. The prompt has two arguments. The first argument passed is the message that will appear in the prompt dialog box (in this case “ Enter your favorite color”)and the second argument is the default value that will appear in the text box( gray in this above program ). In this place you can input your color.
Since the while loop condition is x==”” or x== null , if we didn't give any input the prompt will come again because the condition is true
for loop
for loop executes the statements inside the curly brackets until the condition become false.
for (initialization statement ; condition ; update statement )
{
statements
}
In the above example the 'data' variable is incremented by one in every loop and drawn a line by the color the user has entered through the prompt. When the condition (data < x) become false, the control will come out of the 'for loop'.
document.write(“
”) is to draw a line using the color user has given as input.
while loop.
while loop checks the condition before entering into the loop statements.
In the above example , the numbers are being printed starting from 0 to 4 using the while loop. Document is a built in object and write is a method. Any data passed in the write method gets printed in the browser.
break statement :
break statement is used to terminate the execution of a loop and transfer control to the statement following the loop.
count = 0;
for (i = 0; i < 5 ; i++)
{
if ( i==3) break;
count += i;
}
document.write(count);
count will be 3 because when the if clause become true, the break will get executed and control will go to statement following the loop( in this case - > document.write(count); ).
No comments:
Post a Comment