Is there a While-Loop in JavaScript?
Question by Compi | Last update on 2023-11-01 | Created on 2017-12-16
Does JavaScript know something like a while loop, like it is provided by other programming languages?
I am just trying to translate some code to JavaScript and for this, a while loop would be great. However, something like "while (i < 10) do" seems not to work in JavaScript. The code is just not executed. Can someone help me?
Related Topics
JavaScript: Create and Use Arrays
Info | 0 Comments
JavaScript: Show and hide HTML area by clicking a link
Tutorial | 0 Comments
jQuery: Scroll up and down with and without JavaScript
Tip | 0 Comments
HTML5: Upload Images with Client Side Resize
Tutorial | 9 Comments
jQuery: Disable Submit Button if no Checkbox is selected
Tutorial | 7 Comments
JavaScript: Catch Submit of Form
Tutorial | 0 Comments
Repeat Until Loop in JavaScript?
Question | 1 Answer
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
JavaScript is even offering two different variants of the while loop. However, the syntax "while do" is none of them.
Instead, you can either use the syntax
or alternatively the syntax:
The second variant always executes the code at least once. The condition is checked after the first execution for the first time. Apart from that, when using the first variant, the code will only be executed if the condition is met from the beginning on.
Here is another small example for both ways of implementing while loops in JavaScript:
In both examples, first, the variable i is set to 1 and within each loop, on the one hand, a dialog is displayed showing the current value of the number and on the other hand, the number is increased. The modification will be shown as long as the condition i < 5 is fulfilled.
Important: In any case, make sure that the condition at some time leads to the cancellation of the while loop. Otherwise you get a never-ending loop. For example, if we would set the condition to i > 0 in the example above instead of using the condition i < 5, the loop could never end because i will never fall below the value 0 if i is only always counted up.
Last update on 2023-11-01 | Created on 2017-12-16