Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Loop While

The While Loop

The while loop executes a block of code continuously as long as a given condition remains true.

Syntax

while (condition) {
  // code block to be executed
}

Example

In the following example, the loop will repeatedly execute the code as long as the variable (i) is less than 10.

Example

while (i < 10) {
  text += “The number is “ + i;
  i++;
}
If you forget to increment the variable used in the condition, the loop will run indefinitely, potentially crashing your browser.

The Do While Loop

The do-while loop is a variation of the while loop. It executes the code block once before checking the condition, and then continues to repeat the loop as long as the condition remains true.

Syntax

do {
  // code block to be executed
}
while (condition);

Example

The example below demonstrates a do-while loop, which ensures that the code block runs at least once, even if the condition is false, since the condition is checked only after the code block is executed.

Example

do {
  text += “The number is “ + i;
  i++;
}
while (i < 10);

Make sure to increment the variable used in the condition; otherwise, the loop will run indefinitely!

Comparing For and While

If you’ve read the previous chapter on the for loop, you’ll notice that a while loop is quite similar, with the first and third statements omitted.

The loop in this example utilizes a for loop to gather the car names from the cars array.

Example

const cars = [“BMW”“Volvo”“Saab”“Ford”];
let i = 0;
let text = “”;

for (;cars[i];) {
  text += cars[i];
  i++;
}

This example features a while loop that retrieves the car names from the cars array.

Example

const cars = [“BMW”“Volvo”“Saab”“Ford”];
let i = 0;
let text = “”;

while (cars[i]) {
  text += cars[i];
  i++;
}