Copy. Paste. Copy. Paste. Copy. Paste.
Imagine doing that 500 times just to print numbers from 1 to 500. Sounds exhausting — and completely pointless. Because in coding, there is a smarter way.
It is called a loop. And once you understand it, you will never want to write repetitive code again. In this guide, you will learn exactly what loops are, how they work, and how to use them — with simple examples from the very first step.
What is a loop
in coding?
The concept that saves you from writing the same line a hundred times — and makes you think like a real programmer.
A loop repeats code automatically
A loop is a coding instruction that tells your program to run the same block of code multiple times — without you writing it over and over again.
You write the code once. The loop runs it again and again until you tell it to stop. That’s the whole idea.
I remember when I first came across loops. I was printing numbers 1 to 10 manually — ten separate lines. Then I saw a loop do the same thing in two lines. That moment changed how I thought about coding.
Think of your daily morning routine
Every morning you do the same steps — in the same order. You don’t write a new plan each day. You just repeat the routine automatically.
A loop in code does the exact same thing — runs the same steps over and over so you don’t write them out each time.
Without a loop vs with a loop
Say you want to print “Hello” five times. See how much difference a loop makes:
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")5 lines for 5 prints.
1000 prints = 1000 lines.
for i in range(5):
print("Hello")2 lines for any number.
Change 5 to 1000 — done.
Why do we need loops
in programming?
Without loops, writing even simple programs becomes a nightmare. Here’s exactly why every programmer — beginner or expert — relies on them every single day.
They save you from repeating code
Imagine printing “Good morning” 500 times without a loop. That’s 500 lines of code doing the exact same thing. One loop replaces all of them.
I made this mistake when I first started. I literally copy-pasted the same line 20 times. Then a friend showed me a loop — and I felt embarrassed but immediately understood why loops exist.
They make your code cleaner and easier to read
Clean code is code anyone can read and understand quickly. Loops help keep your code short and organized — no messy, repeated blocks.
Compare these two examples. The loop version is easier to read, fix, and update — especially when working on real projects.
They help you handle large data easily
Real programs work with hundreds or thousands of items — like a list of users, products, or scores. Loops go through every item automatically, no matter the size.
Whether your list has 10 items or 10,000 — the loop code stays exactly the same. That’s what makes loops so powerful in real-world programming.
- ✓ Loop through 10,000 user names in seconds
- ✓ Calculate total price of every item in a cart
- ✓ Find matching records in a large dataset
How does a loop
actually work?
Before writing loops, you need to know what’s happening inside. Let’s break it down into three simple ideas.
The basic structure of a loop
Every loop has the same three parts — a starting point, a condition, and a block of code to run.
Think of it like a machine: you set it up once, turn it on, and it runs until you tell it to stop.
What is a loop condition?
A condition is a yes or no question the loop asks before each run. If the answer is yes — it runs. If no — it stops.
Example: “Is i less than 5?” — as long as yes, the loop keeps going. When i hits 5, the answer is no and it stops.
What is an iteration?
One iteration means one complete run of the loop body. Every time the loop goes around once — that’s one iteration.
If your loop runs 5 times, it has 5 iterations. I used to confuse this with “loop” itself — they’re different. The loop is the machine; the iteration is each turn.
Types of loops
in coding
There are four main loop types. Each one is built for a different job. Pick the right one and your code stays clean and simple.
The for loop — when you know how many times
Use a for loop when you already know exactly how many times the code should run. It’s the most common loop you’ll write.
I use this one almost every day — it’s perfect for counting, going through lists, or repeating a task a fixed number of times.
for i in range(5):
print(i)
# runs exactly 5 timesThe while loop — when you don’t know how many times
A while loop keeps running as long as a condition is true. You don’t need to know the count upfront — it stops on its own when ready.
Think of waiting for user input. You keep asking until they type the right answer — you don’t know how many tries that’ll take.
while answer != "yes":
answer = input("Ready? ")
# stops when condition failsThe do/while loop — run at least once
This loop runs the code first, then checks the condition. That means it always executes at least one time — no matter what.
Perfect for showing a menu or asking for a password. You always want it to run once before checking if the user is done.
do {
password = prompt("Enter:");
} while (password !== "abc");
// always asks at least onceThe for…of loop — the cleaner way to loop arrays
The for…of loop goes through every item in a list directly — no index counter needed. It’s cleaner and easier to read than a regular for loop.
Once I discovered for…of in JavaScript, I stopped using index-based loops for arrays completely. It’s that much simpler.
let names = ["Ali", "Sara"];
for (let name of names) {
console.log(name);
} // cleaner — no i neededFor loop explained
for beginners
The for loop is the most-used loop in coding. Once you get how it works, everything else clicks into place.
For loop in JavaScript — with example
In JavaScript, the for loop has three parts inside the parentheses — start, condition, and update. All three work together to control how many times the loop runs.
This was the first loop I ever wrote. It looked scary at first — but once I understood each part, it became second nature.
for (let i = 0; i < 5; i++) { console.log("Hello number " + i); } // runs 5 times → i = 0, 1, 2, 3, 4
For loop in Python — with example
Python’s for loop is much cleaner — no semicolons, no curly braces. You just use range() to tell it how many times to run.
This simplicity is why Python is great for beginners. The for loop reads almost like plain English — which makes it easy to understand right away.
for i in range(5): print("Hello number", i) # runs 5 times → i = 0, 1, 2, 3, 4
Every for loop has three parts. Miss one and the loop either breaks or runs forever. Here’s exactly what each part does:
Do/While loop
explained for beginners
The do/while loop is different from all other loops. It always runs first — then asks questions. Here’s exactly how it works.
How do/while is different from while
A regular while loop checks the condition first. If it’s false from the start — the code never runs. Not even once.
Do/while runs code before checking
A do/while loop runs the code first, then checks the condition. That means it always executes at least one time — guaranteed.
let i = 10; while (i < 5) { console.log("runs?"); } // never runs — 10 is // already bigger than 5
let i = 10; do { console.log("runs!"); } while (i < 5); // runs ONCE — even // though 10 > 5
When should you use a do/while loop?
Do/while is the rarest loop — but when you need it, nothing else fits as well. Use it when the first run must always happen no matter what.
Looping through arrays
Arrays hold lists of items. Loops go through every item one by one. Together — they’re the most useful combo in coding.
This is the old-school way. You use an index number to reach each item in the array — starting at 0, going up to the last item.
It gives you full control over position. I use this when I need to know exactly which slot I’m on inside the list.
let names = ["Ali", "Sara", "Hamza"]; for (let i = 0; i < names.length; i++) { console.log(names[i]); } // names[0] = "Ali", names[1] = "Sara"...
The for…of loop skips the index completely. It grabs each value directly — no counter, no .length needed. Much cleaner to read.
Once I switched to for…of for arrays, I never went back. It reads almost like plain English — “for each name in names”.
let names = ["Ali", "Sara", "Hamza"]; for (let name of names) { console.log(name); } // no index needed — just the value
Python calls them lists, not arrays — but the idea is the same. Python’s for loop goes through every item directly, with zero setup needed.
No brackets, no i++, no length check. Just “for item in list” — Python handles the rest automatically.
names = ["Ali", "Sara", "Hamza"] for name in names: print(name) # cleanest loop syntax of all
JavaScript arrays have a built-in forEach method that loops through every item automatically. It’s not a loop keyword — it’s a function that does the looping for you.
You’ll see this a lot in real JavaScript projects. Once comfortable with for loops, forEach feels like a natural upgrade.
let names = ["Ali", "Sara", "Hamza"]; names.forEach(function(name) { console.log(name); }); // array loops itself — no for needed
Loop control —
break and continue
Sometimes you need to stop a loop early. Other times, skip one item and move on. That’s exactly what these two keywords are for.
What does break do?
Break stops the loop completely the moment it runs. The loop exits right there — nothing after it runs.
I use this when searching a list. Once I find what I need, there’s no point checking the rest.
for (let i = 1; i <= 5; i++) { if (i === 4) break; console.log(i); } // OUTPUT → 1 2 3
What does continue do?
Continue skips only the current item and jumps to the next one. The loop keeps running — it just skips what you tell it to.
Think of it like skipping a bad song in a playlist — the music doesn’t stop, it just moves on.
for (let i = 1; i <= 5; i++) { if (i === 3) continue; console.log(i); } // OUTPUT → 1 2 4 5
Break vs continue — key difference
They look similar but do completely opposite things. Here’s a clear side-by-side so you never mix them up:
| keyword | what it does | loop after it | use when |
|---|---|---|---|
| break | Exits the entire loop immediately | stops | You found what you needed |
| continue | Skips current item only | keeps going | Skip this one, check the rest |
Common mistakes
beginners make with loops
Every beginner makes these mistakes at least once. Knowing them early saves you hours of confusion later.
Forgetting to update the counter
If you forget to write i++ inside a while loop, the counter never changes. The condition stays true forever — and your program freezes.
I crashed my browser doing this on my first week. The tab froze completely. Always make sure your loop has a way to move forward.
let i = 0; while (i < 5) { console.log(i); // i never updates! // runs forever ♾ }
let i = 0; while (i < 5) { console.log(i); i++; // moves forward // stops at 5 ✓ }
Writing the wrong loop condition
Using i <= 5 instead of i < 5 runs your loop one extra time. This causes wrong outputs or errors — especially with arrays that start at index 0.
Off-by-one errors are super common for beginners. Always double-check your condition before running.
for (let i = 0; i <= 5; i++) { console.log(i); } // prints 0,1,2,3,4,5 // that's 6 runs!
for (let i = 0; i < 5; i++) { console.log(i); } // prints 0,1,2,3,4 // exactly 5 runs ✓
Using the wrong loop type
Using a while loop when a for loop fits better — or vice versa — makes your code harder to read and more likely to break.
Simple rule: know the count → use for. Don’t know when it stops → use while. Pick the right tool and your code stays clean.
let i = 0; while (i < names.length) { console.log(names[i]); i++; } // works but messy
for (let name of names) { console.log(name); } // cleaner — for…of // fits arrays perfectly
Frequently asked
questions about loops
Quick, clear answers to the questions beginners ask most.
A loop is a coding instruction that tells your program to repeat a block of code automatically — without writing it again and again.
You write the code once. The loop runs it as many times as you need — then stops when the condition is no longer true.
An infinite loop is a loop that never stops — because its condition never becomes false. It keeps running forever, freezing or crashing your program.
Two common causes: condition is always true, or you forgot to update the counter inside a while loop.
Fix: always make sure your loop has a clear exit. Press Ctrl + C to stop a frozen loop.
break exits the entire loop immediately — nothing after it runs. continue only skips the current item and moves to the next one — the loop keeps going.
Yes — every major programming language has loops. The syntax looks different, but the idea is exactly the same across all of them.
A nested loop is a loop inside another loop. The inner loop runs completely for every single run of the outer loop.
Think of it like a calendar — for each month (outer loop), you go through every day (inner loop).