For Loop vs While Loop - When to Use Each
Understand the difference between for loops and while loops. Learn when to use each type with clear examples in JavaScript and Python.
Learn2Code Team
December 10, 2025
The Simple Answer
- Use a for loop when you know how many times to repeat
- Use a while loop when you don't know how many times to repeat
For Loops
For loops are perfect when you have a specific number of iterations:
1// Print numbers 1 to 52for (let i = 1; i <= 5; i++) {3 console.log(i);4}5 6// Loop through an array7const fruits = ["apple", "banana", "orange"];8for (let i = 0; i < fruits.length; i++) {9 console.log(fruits[i]);10}In Python:
1# Print numbers 1 to 52for i in range(1, 6):3 print(i)4 5# Loop through a list6fruits = ["apple", "banana", "orange"]7for fruit in fruits:8 print(fruit)When to Use For Loops
- Iterating through arrays or lists
- Repeating something a specific number of times
- When you need an index counter
- Processing each item in a collection
While Loops
While loops continue until a condition becomes false:
1// Keep asking until valid input2let input = "";3while (input !== "yes" && input !== "no") {4 input = prompt("Enter yes or no:");5}6 7// Process until done8let remaining = 100;9while (remaining > 0) {10 const processed = processChunk();11 remaining -= processed;12}In Python:
1# Keep asking until valid input2answer = ""3while answer not in ["yes", "no"]:4 answer = input("Enter yes or no: ")5 6# Read file until empty7line = file.readline()8while line:9 process(line)10 line = file.readline()When to Use While Loops
- User input validation
- Reading data until end of file
- Game loops (run until game over)
- Waiting for a condition to be met
- When you don't know the iteration count upfront
Common Patterns
Counting with For
1// Sum numbers 1 to 1002let sum = 0;3for (let i = 1; i <= 100; i++) {4 sum += i;5}6console.log(sum); // 5050Searching with While
1// Find first even number2const numbers = [1, 3, 5, 8, 9, 11];3let i = 0;4while (i < numbers.length && numbers[i] % 2 !== 0) {5 i++;6}7console.log(numbers[i]); // 8Infinite Loops (Be Careful!)
1// Dangerous - runs forever!2while (true) {3 console.log("This never stops");4}5 6// Safe - has an exit condition7while (true) {8 const input = getInput();9 if (input === "quit") {10 break; // Exit the loop11 }12 process(input);13}For...of and For...in
Modern JavaScript has cleaner ways to loop:
1// For...of - iterate over values2const colors = ["red", "green", "blue"];3for (const color of colors) {4 console.log(color);5}6 7// For...in - iterate over keys/indices8const person = { name: "Alice", age: 25 };9for (const key in person) {10 console.log(`${key}: ${person[key]}`);11}Do...While Loops
Runs at least once, then checks the condition:
1let attempts = 0;2do {3 attempts++;4 const success = tryConnection();5} while (!success && attempts < 3);Performance Considerations
For most cases, performance difference is negligible. Choose based on readability:
1// Both are fine for arrays2// For loop - more control3for (let i = 0; i < arr.length; i++) {4 // Can easily skip, reverse, etc.5}6 7// For...of - cleaner when you just need values8for (const item of arr) {9 // Simpler, more readable10}Quick Reference
| Situation | Best Loop | |-----------|-----------| | Known iteration count | for | | Array/list iteration | for...of | | Object properties | for...in | | Unknown iteration count | while | | Run at least once | do...while | | User input validation | while |
Practice
The best way to master loops is to write them. Try these exercises:
- Print all even numbers from 1 to 20 (for loop)
- Keep generating random numbers until you get one > 0.9 (while loop)
- Sum all numbers in an array (for...of)
Our interactive exercises include plenty of loop challenges to help you build muscle memory for both types.
