JavaScript for loop
In the previous tutorial we have seen about:
- Javascript while loop and
- JavaScript do-while loop.
The JavaScript for loop has three crucial parts, and it is the minimized/compacted form of looping statement.
- Initialization part: is used for declaring and initializing variables.
- Condition/Expression: This is used for Evaluating or testing whether the condition is true or false.
- Iteration: This part is used for increment or decrement of our counter.
SyntaxExample1:Display the first five natural numbers. Output
for (initialization; condition; iteration(inc/dec);) {
statement;
}
<html> <head> <title>JS for loop</title> </head> <body> <script> document.write("--Start--"+"</br>"); for (let i = 1; i <=5; i++) { document.write("Iteration:"+i+"</br>"); document.write("</br>") } document.write("--End--"); </script> </body> </html>
<html> <head> <title>JS for loop</title> </head> <body> <script> var text="JS tutorial!" for (let i = 1; i <=3; i++) { document.write(text+"</br>"); } </script> </body> </html>
<html> <head> <title>JS for loop</title> </head> <body> <script> var sum=0; for (let i = 1; i <=100; i++) { sum+=i; } document.write("Sum="+sum); </script> </body> </html>
0 Comments