</> Code Corner

JavaScript · JS Tutorial · Lesson 31

JS Loop While

while and do...while loops.

The while loop runs as long as a condition is true. do...while always runs at least once.

Example

<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 4) {
  text += "while: " + i + "<br>";
  i++;
}
let j = 10;
do {
  text += "do...while runs once even though j = " + j + "<br>";
  j++;
} while (j < 5);
document.getElementById("demo").innerHTML = text;
</script>
Tip: Always change the variable used in the condition, otherwise the loop never ends (infinite loop) and the browser freezes.

Keep reading “JS Loop While”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋