Learn2Code
learn2code
← Back to Blog
Fundamentals6 min read

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:

code.js
1// Print numbers 1 to 5
2for (let i = 1; i <= 5; i++) {
3 console.log(i);
4}
5 
6// Loop through an array
7const fruits = ["apple", "banana", "orange"];
8for (let i = 0; i < fruits.length; i++) {
9 console.log(fruits[i]);
10}

In Python:

code.py
1# Print numbers 1 to 5
2for i in range(1, 6):
3 print(i)
4 
5# Loop through a list
6fruits = ["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:

code.js
1// Keep asking until valid input
2let input = "";
3while (input !== "yes" && input !== "no") {
4 input = prompt("Enter yes or no:");
5}
6 
7// Process until done
8let remaining = 100;
9while (remaining > 0) {
10 const processed = processChunk();
11 remaining -= processed;
12}

In Python:

code.py
1# Keep asking until valid input
2answer = ""
3while answer not in ["yes", "no"]:
4 answer = input("Enter yes or no: ")
5 
6# Read file until empty
7line = 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

code.js
1// Sum numbers 1 to 100
2let sum = 0;
3for (let i = 1; i <= 100; i++) {
4 sum += i;
5}
6console.log(sum); // 5050

Searching with While

code.js
1// Find first even number
2const 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]); // 8

Infinite Loops (Be Careful!)

code.js
1// Dangerous - runs forever!
2while (true) {
3 console.log("This never stops");
4}
5 
6// Safe - has an exit condition
7while (true) {
8 const input = getInput();
9 if (input === "quit") {
10 break; // Exit the loop
11 }
12 process(input);
13}

For...of and For...in

Modern JavaScript has cleaner ways to loop:

code.js
1// For...of - iterate over values
2const colors = ["red", "green", "blue"];
3for (const color of colors) {
4 console.log(color);
5}
6 
7// For...in - iterate over keys/indices
8const 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:

code.js
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:

code.js
1// Both are fine for arrays
2// For loop - more control
3for (let i = 0; i < arr.length; i++) {
4 // Can easily skip, reverse, etc.
5}
6 
7// For...of - cleaner when you just need values
8for (const item of arr) {
9 // Simpler, more readable
10}

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:

  1. Print all even numbers from 1 to 20 (for loop)
  2. Keep generating random numbers until you get one > 0.9 (while loop)
  3. 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.

#loops#for-loop#while-loop#beginners

Ready to practice what you learned?

Apply these concepts with our interactive coding exercises.

Start Practicing