How to create a while loop in Javascript
How to create a while loop in Javascript
As I said in one my earlier articles, I’ll try porting every script to all programming language we’ve set the category for, this time is for javascript.
Scenario
Create a counting script that stops once it reaches 10 and alerts the user the execution has finished.
Solution
1 2 3 4 5 6 |
var count = 0; while (count < 10) { document.write("Count is: " + count +"<br/>"); count++; } document.write("Count has been completed"); |
Output
1 2 3 4 5 6 7 8 9 10 11 |
Count is: 0 Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count has been completed |
Multiple while loops in javascript
Heads up! Don’t forget that nesting loops within another loop will have the main loop hang (wait) until the nested one is completed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var count = 0; var second = 0; while (count < 4) { while (second < 4) { document.write("Second is: " + second +"<br/>"); second++; } if (second == 4) { second = 0; } document.write("Count is: " + count +"<br/>"); count++; } document.write("Count has been completed"); |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Second is: 0 Second is: 1 Second is: 2 Second is: 3 Count is: 0 Second is: 0 Second is: 1 Second is: 2 Second is: 3 Count is: 1 Second is: 0 Second is: 1 Second is: 2 Second is: 3 Count is: 2 Second is: 0 Second is: 1 Second is: 2 Second is: 3 Count is: 3 Count has been completed |
That’s about it, happy coding!