While Loops in Javascript
Learn about whileloop in javascript with practical examples and code snippets.
Basic 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; while (i < cars.length) { console.log(`${cars[i].brand} -> ${cars[i].name}`); i++; }
While Loop with Condition
Output: Count: 0, 1, 2, 3, 4.
Code
let count = 0; while (count < 5) { console.log(`Count: ${count}`); count++; }
While Loop with Break
Code
let index = 0; while (index < cars.length) { if (cars[index].rating === 5) { console.log(`Found perfect car: ${cars[index].name}`); break; // Exit loop } index++; }
While Loop with Continue
Code
let j = 0; while (j < cars.length) { j++; if (cars[j - 1].rating < 4) { continue; // Skip to next iteration } console.log(`High rated: ${cars[j - 1].name}`); }
Infinite Loop Prevention
Some condition that might never be true.
Code
let counter = 0; const maxIterations = 100; // Safety limit while (counter < maxIterations) { if (someCondition()) { break; } counter++; }
While Loop for Input Validation
In real scenario: input = prompt("Enter your name:");.
Code
function getUserInput() { let input; while (!input || input.trim() === '') { input = "Kuldeep"; // Simulated } return input; }
While Loop for Processing Queue
Code
const queue = [1, 2, 3, 4, 5]; while (queue.length > 0) { const item = queue.shift(); console.log(`Processing: ${item}`); }
Nested While Loops
Common Use Cases 1.
Reading until end of data 2.
Retry logic 3.
Code
let row = 0; while (row < 3) { let col = 0; while (col < 3) { console.log(`[${row}][${col}]`); col++; } row++; } let dataIndex = 0; while (dataIndex < data.length) { processData(data[dataIndex]); dataIndex++; } let attempts = 0; const maxAttempts = 3; while (attempts < maxAttempts) { if (tryOperation()) { break; } attempts++; } let gameRunning = true; while (gameRunning) { updateGame(); if (gameOver()) { gameRunning = false; } }
Summary
Understanding whileloop is essential for mastering javascript. Practice these examples and experiment with variations to deepen your understanding.
Key Takeaways
- whileloop is a fundamental concept in javascript
- Practice with these examples to build confidence
- Experiment with variations to explore edge cases
- Understanding whileloop will help you in technical interviews