Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

7 Loops

3 While Loop

A while loop is a fundamental control flow statement that allows you to execute a block of code repeatedly as long as a specified condition is true. It's particularly useful when you don't know in advance how many times you want to execute the code, and the number of iterations depends on a certain condition.

Here's the basic structure of a while loop:

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

Condition

The condition is evaluated before each iteration of the loop. If the condition evaluates to true, the code inside the loop is executed. If the condition evaluates to false, the loop terminates, and the program continues with the code after the loop.

Example

Let's look at an example:

let i = 0;
while (i < 5) {
    console.log("Iteration: " + i);
    i++; // Incrementing i by 1
}

In this example:

  • Condition: i < 5 specifies that the loop should continue as long as i is less than 5.
  • Inside the loop, we log the value of i and then increment it by 1 (i++).

The loop will execute five times, with i taking on the values 0, 1, 2, 3, and 4 in each iteration. After the fifth iteration, when i becomes 5, the condition i < 5 evaluates to false, and the loop terminates.

While loops are handy when you need to repeat a block of code until a certain condition is met, and the number of iterations isn't predetermined. They allow for flexibility in programming by allowing code execution based on dynamic conditions.