🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

while Loop

AI & DATA SCIENCE // while

The while loop repeats a block as long as its condition is true. The condition is checked before each iteration.

Syntax

while (condition) {
  // loop body
  // update something to eventually make condition false
}

Deep Dive Course

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.

editor.html
// 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);
localhost:3000

2Practical Example

Here is a real-world application of while Loop showing how it is used in production JavaScript code.

editor.html
// 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));
localhost:3000

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.

editor.html
// 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);
localhost:3000

Examples

Example 01Basic Usage
// 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);
Example 02Advanced Example
// 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));

Best Practices

  • Initialize variables before the loop
  • Update the condition variable inside the loop
  • Use do...while if the body must run at least once

Interview Question

When would you choose while over for?

Hint: Unknown number of iterations.

Use while when the number of iterations isn't known upfront — e.g., reading user input, polling until a condition changes, or implementing algorithms like binary search or game loops. Use for when iterating a fixed range or collection.

Exercises

MediumPractice using while Loop in a real scenario.
View Solution
// 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);

Frequently Asked Questions

When would you choose while over for?

Use while when the number of iterations isn't known upfront — e.g., reading user input, polling until a condition changes, or implementing algorithms like binary search or game loops. Use for when iterating a fixed range or collection.

Related Functions

loopsdo-whileforbreakcontinue