What are Loops in Programming? (Explained for Beginners with Example)

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.

📖 Simple definition

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.

☀️ Real-life analogy

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.

💤
Wake up
→
🚿
Shower
→
👓
Get dressed
→
🍳
Breakfast
→
🚪
Leave home
Repeats every morning — just like a loop

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.

💻 Code comparison

Without a loop vs with a loop

Say you want to print “Hello” five times. See how much difference a loop makes:

Without a loop
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")

5 lines for 5 prints.
1000 prints = 1000 lines.

With a loop
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.

💾 Save time

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.

500
lines without a loop
3
lines with a loop
99%
less code to write
👁️ Clean code

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.

# messy — without loop print(“Item 1”) print(“Item 2”) print(“Item 3”)# clean — with loop for i in range(1, 4): print(f”Item {i}“)
📊 Large data

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
⚙ step-by-step

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.

1
Structure

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.

2
Condition

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.

3
Iteration

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.

1run
→
2run
→
3run
→
✓
// loop anatomy — Python
for  i  in  range ( 5 ):
     print ( i )   # runs once per iteration
for i in
Start — sets up the counter variable
range(5)
Condition — run 5 times then stop
print(i)
Body — code that runs each iteration
🔄 loop types

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.

🔁
for loop

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 times
✅ Use when count is fixed
❓
while loop

The 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 fails
✅ Use when count is unknown
▶️
do/while loop

The 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 once
✅ Use when first run is required
🔖
for…of loop

The 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 needed
✅ Use when looping an array
for
Fixed count — you decide how many
while
Unknown count — stops on condition
do/while
Always runs once — checks after
for…of
Arrays — cleanest syntax available
for loop

For 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.

JavaScript

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.

forloop.js
for (let i = 0; i < 5; i++) {
  console.log("Hello number " + i);
}
// runs 5 times → i = 0, 1, 2, 3, 4
OUTPUT → Hello number 0  Hello number 1  Hello number 2  …
Python

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.

forloop.py
for i in range(5):
    print("Hello number", i)
# runs 5 times → i = 0, 1, 2, 3, 4
OUTPUT → Hello number 0  Hello number 1  Hello number 2  …
🔬
Breaking down each part of a for loop
Three parts — each one has a specific job

Every for loop has three parts. Miss one and the loop either breaks or runs forever. Here’s exactly what each part does:

Part 01
let i = 0
Start
Sets the counter to a starting value. Runs only once at the very beginning.
Part 02
i < 5
Condition
Checked before each run. If true — loop continues. If false — loop stops.
Part 03
i++
Update
Runs after each loop cycle. Moves the counter forward so the loop can stop.
Start: i=0 → Check: i<5? → Run code → Update: i++ → Check again… → Stop at 5
do / while loop

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.

while loop

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.

Check condition → happens first
Run code → only if true
Stop if false → may never run
do/while loop

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.

Run code first → always once
Check condition → checked after
Stop if false → exits cleanly
dowhile.js
JavaScript
while loop
let i = 10;

while (i < 5) {
  console.log("runs?");
}
// never runs — 10 is
// already bigger than 5
do/while loop
let i = 10;

do {
  console.log("runs!");
} while (i < 5);
// runs ONCE — even
// though 10 > 5
Key diff → while = 0 runs  |  do/while = 1 run guaranteed
when to use

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.

✅ Asking user for a password — always ask at least once
✅ Showing a menu — display it once before checking user’s choice
❌ Looping through an array — use for or for…of instead
❌ Fixed number of repeats — a regular for loop is cleaner
Beginner tip: Master the for and while loops first. Come back to do/while once you hit a situation where the first run must always happen — you’ll know exactly when you need it.
arrays + loops

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.

🔁
classic
Classic for loop with arrays
›

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.

classic.js
let names = ["Ali", "Sara", "Hamza"];

for (let i = 0; i < names.length; i++) {
  console.log(names[i]);
}
// names[0] = "Ali", names[1] = "Sara"...
output → Ali   Sara   Hamza
✨
cleaner
For…of loop — cleaner and simpler
›

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”.

forof.js
let names = ["Ali", "Sara", "Hamza"];

for (let name of names) {
  console.log(name);
}
// no index needed — just the value
output → Ali   Sara   Hamza
🐍
Python
Python for loop with lists
›

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.

loop.py
names = ["Ali", "Sara", "Hamza"]

for name in names:
    print(name)

# cleanest loop syntax of all
output → Ali   Sara   Hamza
🆕
bonus
forEach method — bonus JavaScript
›
⭐ bonus method

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.

foreach.js
let names = ["Ali", "Sara", "Hamza"];

names.forEach(function(name) {
  console.log(name);
});
// array loops itself — no for needed
output → Ali   Sara   Hamza
loop control

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.

⏹ break

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.

1
2
3
4
5
⏹ break fires at 4 → 5 never runs
for (let i = 1; i <= 5; i++) {
  if (i === 4) break;
  console.log(i);
}
// OUTPUT → 1  2  3
output → 1   2   3   (stops)
⏭ continue

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.

1
2
3
4
5
⏭ 3 is skipped → loop continues
for (let i = 1; i <= 5; i++) {
  if (i === 3) continue;
  console.log(i);
}
// OUTPUT → 1  2  4  5
output → 1   2   4   5   (3 skipped)
key difference

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:

keywordwhat it doesloop after ituse when
breakExits the entire loop immediatelystopsYou found what you needed
continueSkips current item onlykeeps goingSkip this one, check the rest
Memory trick: break = walk off the field entirely. continue = skip your turn but stay in the game.
common mistakes

Common mistakes
beginners make with loops

Every beginner makes these mistakes at least once. Knowing them early saves you hours of confusion later.

⚀ Mistake 01 — infinite loop high risk

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.

✓ Fix: always update i inside the loop
❌ wrong — freezes
let i = 0;
while (i < 5) {
  console.log(i);
  // i never updates!
  // runs forever ♾
}
✓ correct — works fine
let i = 0;
while (i < 5) {
  console.log(i);
  i++; // moves forward
  // stops at 5 ✓
}
❓ Mistake 02 — wrong condition very common

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.

✓ Fix: trace the loop manually once
❌ wrong — 1 extra run
for (let i = 0; i <= 5; i++) {
  console.log(i);
}
// prints 0,1,2,3,4,5
// that's 6 runs!
✓ correct — 5 runs
for (let i = 0; i < 5; i++) {
  console.log(i);
}
// prints 0,1,2,3,4
// exactly 5 runs ✓
🔄 Mistake 03 — wrong loop type easy to avoid

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.

✓ Fix: match the loop to the task
❌ wrong tool — messy
let i = 0;
while (i < names.length) {
  console.log(names[i]);
  i++;
}
// works but messy
✓ right tool — clean
for (let name of names) {
  console.log(name);
}
// cleaner — for…of
// fits arrays perfectly
frequently asked 05

Frequently asked
questions about loops

Quick, clear answers to the questions beginners ask most.

Q1 How do you define a loop? +
definition

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.

for i in range(3): print(“Hello”) # prints Hello 3 times
Q2 What is an infinite loop? +
danger

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.

let i = 0; while (i < 5) { console.log(i); // i never updates → runs forever! }

Fix: always make sure your loop has a clear exit. Press Ctrl + C to stop a frozen loop.

Q3 What is the difference between break and continue? +
control

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.

break = quit the loop entirely continue = skip one, keep going
Q4 Are loops used in all programming languages? +
universal

Yes — every major programming language has loops. The syntax looks different, but the idea is exactly the same across all of them.

Python JavaScript Java C++ PHP Ruby …and every other language
Q5 What is a nested loop? +
advanced

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).

for i in range(3): # outer for j in range(2): # inner print(i, j) # inner runs 2x for each outer run