DEV Community

Madhan Raj
Madhan Raj

Posted on

While Looping In Javascript

JavaScript Loops

Loops in JavaScript allow a block of code to run multiple times as long as a given condition is satisfied. They help reduce repetition and make programs more efficient and organized.

Loops continue running until the condition becomes false.
They are useful for iterating over arrays, strings, and ranges of values.
Enter fullscreen mode Exit fullscreen mode

1. for Loop
1.1 for in loop
1.2 For each loop
2. while Loop
3. do-while Loop

While Loop
The while loop loops through a block of code as long as a specified condition is true.

While loop starts with the checking of Boolean condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loop
Once the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
Enter fullscreen mode Exit fullscreen mode

Syntax

 while (condition) {
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode

Example

while (i < 10) {
  text += "The number is " + i;
  i++;
}
Enter fullscreen mode Exit fullscreen mode

📝 Basic Example

let count = 0;

while (count < 3) {
  console.log("Count is: " + count);
  count++; // Updates the variable so the condition eventually becomes false
}

Enter fullscreen mode Exit fullscreen mode

output

Count is: 0
Count is: 1
Count is: 2

Enter fullscreen mode Exit fullscreen mode

Top comments (0)