JavaScript While Loop


Loops are used to repeatedly run a set of instructions as long as a specific condition remains true.


The While Loop

The code in the while loop keeps repeating as long as a certain condition is true.

Syntax

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

Example

In this example, the code inside the loop will keep running repeatedly as long as a variable (i) is less than 10.

If you don't make the variable bigger in the condition, the loop won't stop. This can make your browser crash.


The Do While Loop

The do while loop works like the while loop. In this loop, the code block is executed once before checking if the specified condition is true. After that, the loop will continue to repeat as long as the condition remains true.

Syntax

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

Example

The code example below employs a "do while" loop. This type of loop ensures that the code block is executed at least once, regardless of whether the condition is initially false or true. The code runs before checking the condition.

Remember to increment the variable mentioned in the condition; otherwise, the loop will continue indefinitely!


Comparing For and While

If you've gone through the earlier section on the for loop, you'll find that a while loop is quite similar. The only difference is that it doesn't have statement 1 and statement 3.

In this instance, a loop is employed with the for loop to gather the names of cars from the array called "cars."

The example here uses a while loop in the code to gather car names from the array called cars.