DEV Community

Cover image for Understanding While Loops in JavaScript
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Understanding While Loops 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.In JavaScript, there are three types of Loops :

1.for loop
2.while loop
3.do-while loop
In this section we see while loop.

while loop
A while loop in JavaScript executes a block of code repeatedly as long as a specified condition evaluates to true. It is an entry-controlled loop, meaning the browser evaluates the condition before running any code inside the loop body.

Syntax

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

Examples

let count = 1;
while (count <= 5) {
  console.log(count);
  count++;//1 2 3 4 5
}
Enter fullscreen mode Exit fullscreen mode
let i = 1;

while (i < 4) {
  console.log(i); 
  i++; // Increments i so the condition eventually becomes false
}

// Output:
// 1
// 2
// 3
Enter fullscreen mode Exit fullscreen mode
let total = 0;
let i = 1;

while (i <= 5) {
    total = total + i; // Very simple math
    i = i + 1;         // Moves to the next number
}

console.log(total); // Prints: 15
Enter fullscreen mode Exit fullscreen mode

Avoiding Infinite Loops
If your condition never turns false, your code will enter an infinite loop, freezing your browser or application.

// ⚠️ INFINITE LOOP WARNING
let count = 1;
while (count <= 5) {
  console.log(count);
  // Missing count++ means count stays 1 forever!
}
Enter fullscreen mode Exit fullscreen mode

References
https://www.geeksforgeeks.org/javascript/loops-in-javascript/

Top comments (0)