Use **while** when you don't know in advance how many iterations you need. The condition is evaluated **before** each iteration — if it's false from the start, the body never runs. Always ensure the loop body changes something that eventually makes the condition false.
1Understanding while Loop
Use while when you don't know in advance how many iterations you need. The condition is evaluated before each iteration — if it's false from the start, the body never runs. Always ensure the loop body changes something that eventually makes the condition false.
If your while loop runs forever, it will freeze the browser or crash Node.js. Always ensure the exit condition is reachable.
// Read until we find a prime
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
let num = 10;
while (!isPrime(num)) { num++; }
console.log('First prime >= 10:', num);2Practical Example
Here is a real-world application of while Loop showing how it is used in production JavaScript code.
// Binary search uses while naturally
function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
console.log(binarySearch([1,3,5,7,9,11], 7));3Best Practices
Follow these guidelines when working with while Loop:
1. Initialize variables before the loop
2. Update the condition variable inside the loop
3. Use do...while if the body must run at least once
Tip: If your while loop runs forever, it will freeze the browser or crash Node.js. Always ensure the exit condition is reachable.
// Read until we find a prime
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
let num = 10;
while (!isPrime(num)) { num++; }
console.log('First prime >= 10:', num);