22 Votes

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?

ReplyPositiveNegative
2Best Answer2 Votes

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

while (condition) {
  code
}

or alternatively the syntax:

do {
  code
} while (condition);

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:

// variant 1
var i = 1;

while (i < 5) {
  alert(i);
  i++;
}

// variant 2
var i = 1;

do {
  alert(i);
  i++;
} while (i < 5);

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

ReplyPositive Negative
Reply

Related Topics

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.