Dowhile in Javascript
Learn about dowhile in javascript with practical examples and code snippets.
Basic Do-While Loop
Code
const cars = [ { id: 1, name: "Nexon", brand: "Tata", make: "2017", rating: 2 }, { id: 2, name: "Verna", brand: "Hyundai", make: "2008", rating: 4 }, { id: 3, name: "Bolero", brand: "Mahindra", make: "2012", rating: 5 }, { id: 4, name: "Baleno", brand: "Maruti", make: "2022", rating: 4 }, { id: 5, name: "Seltos", brand: "Kia", make: "2011", rating: 3 }, { id: 6, name: "G-class", brand: "Mercedes", make: "2024", rating: 5 } ]; let i = 0; do { console.log(`${cars[i].brand} -> ${cars[i].name}`); i++; } while (i < cars.length);
Do-While Executes at Least Once
Output: Count: 0 Compare with while loop No output - doesn't execute.
Code
let count = 0; do { console.log(`Count: ${count}`); count++; } while (count < 0); // Condition is false, but still executes once let count2 = 0; while (count2 < 0) { console.log(`Count: ${count2}`); count2++; }
Menu System (Common Use Case)
Display menu In real scenario: choice = getUserInput();.
Code
function showMenu() { let choice; do { console.log("1. Option 1"); console.log("2. Option 2"); console.log("3. Exit"); choice = "3"; // Simulated if (choice === "1") { console.log("Executing option 1"); } else if (choice === "2") { console.log("Executing option 2"); } } while (choice !== "3"); console.log("Exiting menu"); }
Input Validation
In real scenario: number = parseInt(prompt("Enter a number between 1-10:"));.
Code
function getValidNumber() { let number; do { number = 5; // Simulated } while (number < 1 || number > 10); return number; }
Processing Until Condition
Output: Value: 10, 8, 6, 4, 2.
Code
let value = 10; do { console.log(`Value: ${value}`); value -= 2; } while (value > 0);
Retry Logic
success = tryOperation();.
Code
let attempts = 0; let success = false; const maxAttempts = 3; do { attempts++; console.log(`Attempt ${attempts}`); success = attempts === 2; // Simulated } while (!success && attempts < maxAttempts); if (success) { console.log("Operation succeeded"); } else { console.log("Operation failed after max attempts"); }
Array Processing
When to Use Do-While ✅ Use when you need to execute code at least once ✅ Use for menu systems ✅ Use for input validation ✅ Use when condition depends on code execution ❌ Don't use when condition might be false initially and you don't want execution Use while loop instead in that case.
Code
let index = 0; do { if (index < cars.length) { console.log(cars[index].name); } index++; } while (index < cars.length);
Summary
Understanding dowhile is essential for mastering javascript. Practice these examples and experiment with variations to deepen your understanding.
Key Takeaways
- dowhile is a fundamental concept in javascript
- Practice with these examples to build confidence
- Experiment with variations to explore edge cases
- Understanding dowhile will help you in technical interviews