Skip to main content

Syntax for while loop

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

The while loop can be thought of as a repeating if statement.

The basic syntax of a while loop:

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

Explanation:

  • The while loop starts with i equal to 1. The loop will continue to execute as long as i is less than or equal to 5.
  • In each iteration of the loop, the value of i is printed to the console using console.log(i), and then i is incremented by 1 using the i++ shorthand for i = i + 1.

Here's what each part of the while loop does:

  • condition: This is a condition that is evaluated before each iteration of the loop. If the condition is true, the loop will execute; otherwise, the loop will terminate.
  • code to be executed: This is the code that will be executed in each iteration of the loop as long as the condition is true.

Here's an example of a while loop that counts from 1 to 5 and prints each number to the console:

let i = 1;

while (i <= 5) {
console.log(i);
i++;
}

In this example:

  • The while loop starts with i equal to 1. The loop will continue to execute as long as i is less than or equal to 5.
  • In each iteration of the loop, the value of i is printed to the console using console.log(i), and then i is incremented by 1 using the i++ shorthand for i = i + 1.

You can also use a while loop to iterate over the elements of an array:

const numbers = [1, 2, 3, 4, 5];
let i = 0;

while (i < numbers.length) {
console.log(numbers[i]);
i++;
}

In this example:

  • The while loop starts with i equal to 0. The loop will continue to execute as long as i is less than the length of the numbers array.
  • In each iteration of the loop, the value of numbers[i] is printed to the console using console.log(numbers[i]), and then i is incremented by 1 using the i++ shorthand for i = i + 1.

The Do While Loop

The do...while loop is similar to the while loop, but it guarantees that the loop body will be executed at least once, even if the condition is initially false.

The basic syntax of the do...while loop is:

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

The loop will continue to execute the code block as long as the condition remains true.

However, the code block will always be executed at least once, regardless of the initial state of the condition.

Here is an example that uses a do...while loop to display the numbers from 1 to 5 in the console:

let i = 1;

do {
console.log(i);
i++;
} while (i <= 5);

In this example:

  • The loop will execute at least once, even though the condition i <= 5 is initially false.
  • The loop will continue to execute as long as i is less than or equal to 5, and each iteration will increment the value of i by 1. The output of this code in the console will be:
1
2
3
4
5