Loop Method
- For Loop
- While Loop
- Do While Loop
1.For Loop Statement
For Loop usually used to create a loop
-example code
for(statement1;statement2;statement3){
code for loop
}
statement1 : is executed before the loop running
statement2 : define the condition for running the loop
statement3 : to executed each time after the loop
Example
Explaination
var i is define the variable for i (numeric)
i<=10 loop the code less than equals 10 times
i++ to make variable i added with 1
example
var i=2;
result=i++;
document.write(result);
///Output 3
2.While Loop
while loop similar with For Loop but this statement will work if the condition is true
Example
While(Condition){
code to loop
}
the result statement is always True or False
example
the loop will run as long as variable i less than 10 and don't forget to increase the value of variable i,
if you forget to increase the variable , the loop will do the infinite loop, and it will make the program error
3.Do While Loop
the different between while loop, this method will execute the codeblock once and check the condition on statement While
Example
Do{
code block
}
while(condition)
Example
the code will executed once ,before check the condition
see the "Hello World" first,not show the number first because it's first executed
Conclusion
the summary is if you want to loop some codeblock , and you want to decide what the method will you used, it depend on what's the data that you used, and you have be careful if use the loop method, because can make the fatal Error ,for example is Infinite loop, the code will repeat infinite.
keep clean and Cheers !
Learn JavaScript IV (Looping)
4/
5
Oleh
Fata EL Islami