Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /While Do While Loops
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

While and Do-While Loops

Condition-based iteration in JavaScript

While for loops are great when you know exactly how many times to repeat, while and do-while loops are perfect when you want to repeat code as long as a condition is true. They're ideal for validating user input, reading data until done, or repeating actions until a goal is met. Let's master condition-based loops!

While Loop

A while loop repeats code as long as a condition is true. The condition is checked before each iteration.

Syntax

JAVASCRIPT
while (condition) {
  // Code to repeat
  // Must change condition eventually!
}

// Example
let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}
// Output: 0, 1, 2, 3, 4

How While Loops Work

  1. Check condition
  2. If true, execute code block
  3. Go back to step 1
  4. If false, exit loop
JAVASCRIPT
let i = 0;
while (i < 3) {
  console.log("Iteration:", i);
  i++;
}

// Step by step:
// 1. Check: 0 < 3? Yes → execute
//    Output: "Iteration: 0", i becomes 1
// 2. Check: 1 < 3? Yes → execute
//    Output: "Iteration: 1", i becomes 2
// 3. Check: 2 < 3? Yes → execute
//    Output: "Iteration: 2", i becomes 3
// 4. Check: 3 < 3? No → stop

Basic While Loop Examples

JAVASCRIPT
// Count to 5
let count = 1;
while (count <= 5) {
  console.log(count);
  count++;
}
// Output: 1, 2, 3, 4, 5

// Countdown
let countdown = 5;
while (countdown > 0) {
  console.log(countdown);
  countdown--;
}
console.log("Liftoff!");
// Output: 5, 4, 3, 2, 1, Liftoff!

// Sum until threshold
let sum = 0;
let num = 1;
while (sum < 50) {
  sum += num;
  num++;
}
console.log("Sum:", sum);      // 55
console.log("Numbers used:", num - 1);  // 10

// Process while condition is met
let password = "";
let attempts = 0;
while (password !== "secret" && attempts < 3) {
  // password = prompt("Enter password:");
  password = "secret";  // Simulating user input
  attempts++;
}
console.log("Attempts:", attempts);

While vs For Loop

While loops and for loops can often accomplish the same task, but they're suited for different scenarios.

Choose based on what you know

For Loop (Count-Based)

// For loop - know iterations
for (let i = 0; i < 5; i++) {
  console.log(i);
}

// Count-based iteration
let array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

// Clear start and end
for (let i = 1; i <= 10; i++) {
  console.log(i * 2);
}
Output:
Not run yet...

While Loop (Condition-Based)

// While loop - unknown iterations
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

// Condition-based iteration
let found = false;
let j = 0;
while (!found && j < array.length) {
  if (array[j] === 3) found = true;
  j++;
}

// Continue until condition met
let sum = 0;
let k = 1;
while (sum < 50) {
  sum += k;
  k++;
}
Output:
Not run yet...

Use For Loop When:

  • You know exact number of iterations
  • Iterating through arrays/collections
  • Counter-based iteration
  • Standard counting patterns

Use While Loop When:

  • Number of iterations unknown
  • Loop until specific condition met
  • Waiting for user input
  • Processing until data exhausted
  • Game loops and simulations

Do-While Loop

A do-while loop is similar to a while loop, but it checks the condition after executing the code block. This means it always runs at least once.

Syntax

JAVASCRIPT
do {
  // Code to execute
  // Runs at least once!
} while (condition);

// Example
let count = 0;
do {
  console.log(count);
  count++;
} while (count < 5);
// Output: 0, 1, 2, 3, 4

Key Difference: Execute First, Check After

JAVASCRIPT
// While loop - might not run at all
let i = 10;
while (i < 5) {
  console.log("While:", i);  // Never executes
}
console.log("While loop didn't run");

// Do-while loop - always runs once
let j = 10;
do {
  console.log("Do-while:", j);  // Executes once!
} while (j < 5);
console.log("Do-while ran once");

// Output:
// "While loop didn't run"
// "Do-while: 10"
// "Do-while ran once"

Remember: Do-while loops ALWAYS execute at least once because the condition is checked after the code runs. Use this when you need guaranteed first execution.

Do-While Examples

JAVASCRIPT
// Menu that must display at least once
let choice;
do {
  console.log("Menu:");
  console.log("1. New Game");
  console.log("2. Load Game");
  console.log("3. Exit");
  // choice = prompt("Choose option:");
  choice = "3";  // Simulating user input
} while (choice !== "3");
console.log("Goodbye!");

// Validate input - must ask at least once
let age;
do {
  // age = prompt("Enter your age:");
  age = 25;  // Simulating valid input
} while (age < 0 || age > 120);
console.log("Valid age:", age);

// Retry mechanism
let attempts = 0;
let success = false;
do {
  console.log("Attempt:", attempts + 1);
  // Try operation
  success = Math.random() > 0.7;  // 30% success rate
  attempts++;
} while (!success && attempts < 5);

if (success) {
  console.log("Success after", attempts, "attempts");
} else {
  console.log("Failed after", attempts, "attempts");
}

// Generate random until condition met
let randomNum;
let count = 0;
do {
  randomNum = Math.floor(Math.random() * 10);
  count++;
  console.log("Generated:", randomNum);
} while (randomNum !== 7);
console.log("Found 7 after", count, "tries");

Avoiding Infinite Loops

An infinite loop runs forever because its condition never becomes false. This crashes your program!

Common Infinite Loop Mistakes

JAVASCRIPT
// WRONG: Forgot to increment
// let i = 0;
// while (i < 5) {
//   console.log(i);
//   // i never changes! Infinite loop!
// }

// WRONG: Incrementing wrong direction
// let j = 0;
// while (j < 10) {
//   console.log(j);
//   j--;  // Going backwards! Infinite loop!
// }

// WRONG: Condition always true
// let k = 0;
// while (k >= 0) {
//   console.log(k);
//   k++;  // k is always >= 0! Infinite loop!
// }

// WRONG: Never updating condition variable
// let found = false;
// while (!found) {
//   console.log("Searching...");
//   // found never changes! Infinite loop!
// }

// RIGHT: Proper increment
let i = 0;
while (i < 5) {
  console.log(i);
  i++;  // Changes in right direction
}

// RIGHT: Eventually becomes false
let found = false;
let attempts = 0;
while (!found && attempts < 10) {
  console.log("Attempt:", attempts);
  found = Math.random() > 0.8;  // Might become true
  attempts++;  // Safety: stops after 10 tries
}

Safety Patterns

JAVASCRIPT
// Pattern 1: Maximum iterations
let maxAttempts = 100;
let attempts = 0;
let result = null;

while (result === null && attempts < maxAttempts) {
  // Try to get result
  result = tryGetResult();
  attempts++;
}

if (result) {
  console.log("Success:", result);
} else {
  console.log("Failed after", maxAttempts, "attempts");
}

// Pattern 2: Timeout
let startTime = Date.now();
let timeout = 5000;  // 5 seconds

while (Date.now() - startTime < timeout) {
  // Do work
  if (checkIfDone()) {
    break;  // Exit when done
  }
}

// Pattern 3: Break condition
while (true) {
  let value = getNextValue();
  
  if (value === null) {
    break;  // Exit when no more values
  }
  
  processValue(value);
}

// Pattern 4: External flag
let keepRunning = true;
let iteration = 0;

while (keepRunning) {
  console.log("Running:", iteration);
  iteration++;
  
  if (iteration >= 10) {
    keepRunning = false;  // Stop condition
  }
}

How to stop an infinite loop:

  • In browser: Close the tab
  • In Node.js: Press Ctrl+C
  • In VS Code: Click the stop button

Prevention: Always ensure your loop variable changes in a way that makes the condition false eventually!

Practical While Loop Patterns

Pattern 1: Input Validation

JAVASCRIPT
function getValidNumber(min, max) {
  let num;
  let isValid = false;
  
  while (!isValid) {
    // num = prompt(`Enter number between ${min} and ${max}:`);
    num = 50;  // Simulating input
    num = Number(num);
    
    if (!isNaN(num) && num >= min && num <= max) {
      isValid = true;
    } else {
      console.log("Invalid! Try again.");
      break;  // For demo purposes
    }
  }
  
  return num;
}

// let age = getValidNumber(0, 120);
// console.log("Valid age:", age);

// Email validation loop
function getValidEmail() {
  let email;
  let isValid = false;
  
  while (!isValid) {
    // email = prompt("Enter email:");
    email = "user@example.com";  // Simulating input
    
    if (email.includes("@") && email.includes(".")) {
      isValid = true;
    } else {
      console.log("Invalid email format");
      break;  // For demo purposes
    }
  }
  
  return email;
}

// let email = getValidEmail();
// console.log("Valid email:", email);

Pattern 2: Processing Until Done

JAVASCRIPT
// Read data until end marker
function processData(data) {
  let index = 0;
  let results = [];
  
  while (index < data.length && data[index] !== "END") {
    results.push(data[index].toUpperCase());
    index++;
  }
  
  return results;
}

let data = ["apple", "banana", "END", "orange"];
console.log(processData(data));  // ["APPLE", "BANANA"]

// Process queue until empty
function processQueue(queue) {
  let processed = 0;
  
  while (queue.length > 0) {
    let item = queue.shift();  // Remove first item
    console.log("Processing:", item);
    processed++;
  }
  
  return processed;
}

let queue = ["task1", "task2", "task3"];
console.log("Processed:", processQueue(queue), "items");

// Search until found or exhausted
function findInArray(array, target) {
  let index = 0;
  let found = false;
  
  while (index < array.length && !found) {
    if (array[index] === target) {
      found = true;
    } else {
      index++;
    }
  }
  
  return found ? index : -1;
}

let numbers = [5, 10, 15, 20, 25];
console.log("Index of 15:", findInArray(numbers, 15));  // 2
console.log("Index of 99:", findInArray(numbers, 99));  // -1

Pattern 3: Accumulation with Condition

JAVASCRIPT
// Sum numbers until threshold
function sumUntilThreshold(threshold) {
  let sum = 0;
  let num = 1;
  let numbersUsed = [];
  
  while (sum < threshold) {
    sum += num;
    numbersUsed.push(num);
    num++;
  }
  
  return {
    sum: sum,
    count: numbersUsed.length,
    numbers: numbersUsed
  };
}

console.log(sumUntilThreshold(50));
// { sum: 55, count: 10, numbers: [1,2,3,4,5,6,7,8,9,10] }

// Build string until max length
function buildString(words, maxLength) {
  let result = "";
  let index = 0;
  
  while (index < words.length && result.length < maxLength) {
    let nextWord = words[index];
    
    if (result.length + nextWord.length <= maxLength) {
      result += (result ? " " : "") + nextWord;
      index++;
    } else {
      break;
    }
  }
  
  return result;
}

let words = ["The", "quick", "brown", "fox", "jumps"];
console.log(buildString(words, 15));  // "The quick brown"

Pattern 4: Game Loop

JAVASCRIPT
// Simple number guessing game
function guessingGame() {
  let target = Math.floor(Math.random() * 100) + 1;
  let guesses = 0;
  let maxGuesses = 10;
  let won = false;
  
  console.log("Guess the number between 1 and 100!");
  
  while (guesses < maxGuesses && !won) {
    guesses++;
    // let guess = prompt(`Guess #${guesses}:`);
    let guess = target;  // Auto-win for demo
    guess = Number(guess);
    
    if (guess === target) {
      won = true;
      console.log(`You won in ${guesses} guesses!`);
    } else if (guess < target) {
      console.log("Too low!");
    } else {
      console.log("Too high!");
    }
  }
  
  if (!won) {
    console.log(`Game over! The number was ${target}`);
  }
  
  return { won, guesses };
}

// guessingGame();

// Coin flip game
function coinFlipGame(targetWins) {
  let wins = 0;
  let losses = 0;
  let flips = 0;
  
  while (wins < targetWins) {
    flips++;
    let result = Math.random() < 0.5 ? "heads" : "tails";
    
    if (result === "heads") {
      wins++;
      console.log(`Flip ${flips}: Heads! (Wins: ${wins})`);
    } else {
      losses++;
      console.log(`Flip ${flips}: Tails (Losses: ${losses})`);
    }
  }
  
  return { wins, losses, flips };
}

console.log(coinFlipGame(3));

Practical Examples

Example 1: Password Checker with Retry

JAVASCRIPT
function checkPassword(correctPassword, maxAttempts = 3) {
  let attempts = 0;
  let isAuthenticated = false;
  
  do {
    attempts++;
    // let password = prompt(`Enter password (Attempt ${attempts}/${maxAttempts}):`);
    let password = attempts === 2 ? correctPassword : "wrong";
    
    if (password === correctPassword) {
      isAuthenticated = true;
      console.log("✓ Access granted!");
    } else {
      let remaining = maxAttempts - attempts;
      if (remaining > 0) {
        console.log(`✗ Wrong password. ${remaining} attempts remaining.`);
      }
    }
  } while (!isAuthenticated && attempts < maxAttempts);
  
  if (!isAuthenticated) {
    console.log("✗ Account locked. Too many failed attempts.");
  }
  
  return {
    authenticated: isAuthenticated,
    attempts: attempts
  };
}

console.log(checkPassword("secret123"));

Example 2: Data Processor with Validation

JAVASCRIPT
function processOrders(orders) {
  let index = 0;
  let processed = [];
  let failed = [];
  
  while (index < orders.length) {
    let order = orders[index];
    
    // Validate order
    if (!order.id || !order.total || order.total <= 0) {
      failed.push({
        order: order,
        reason: "Invalid order data"
      });
      index++;
      continue;
    }
    
    // Process valid order
    let processedOrder = {
      id: order.id,
      total: order.total,
      tax: order.total * 0.08,
      finalTotal: order.total * 1.08,
      status: "processed"
    };
    
    processed.push(processedOrder);
    index++;
  }
  
  return {
    processed: processed,
    failed: failed,
    summary: {
      total: orders.length,
      success: processed.length,
      failed: failed.length
    }
  };
}

let orders = [
  { id: 1, total: 50 },
  { id: 2, total: -10 },  // Invalid
  { id: 3, total: 100 },
  { total: 75 }  // Missing id
];

console.log(processOrders(orders));

While and Do-While Practice

Experiment with condition-based loops

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Key Takeaways

  • While loops check condition before execution
  • Do-while loops check condition after execution (runs at least once)
  • Use while when you don't know how many iterations needed
  • Use do-while when you must execute at least once
  • Always ensure loop variable changes to prevent infinite loops
  • Add safety limits (max iterations, timeout) for protection
  • While loops are perfect for validation and condition-based processing
  • For loops are better when you know exact iteration count
  • Use break to exit loops early when condition is met
  • Test your loop conditions carefully to avoid infinite loops

What's Next?

You now understand how to use while and do-while loops for condition-based iteration! These loops are essential when you don't know in advance how many times you need to repeat code.

In the next lesson, we'll explore For...of and For...in Loops—modern JavaScript loops designed specifically for iterating over arrays, strings, and object properties. They're cleaner and more intuitive than traditional for loops for many common tasks!

💪 Practice Challenge:

Before moving on, try creating:

  1. A function that keeps asking for input until it's valid (age between 0-120)
  2. A number guessing game using a while loop
  3. A function that processes an array until it finds a specific value
  4. A do-while loop that displays a menu until user chooses "exit"
  5. A function that simulates rolling dice until you get a 6

Test Your Understanding

Question 1 / 4

What's the main difference between while and for loops?

Score: 0 / 0

Learning JavaScript while loops! 🔄

Previous
For Loops
Next
For...of and For...in Loops

Continue Learning JavaScript

Join 2,000+ developers mastering JavaScript loops and iteration. New lessons weekly - 100% FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo