Understand what loops are, why they’re used in programming, and how they help you write cleaner, smarter code.
In JavaScript (and most programming languages), loops allow you to repeat a block of code multiple times without having to write it again and again.
Let’s say you want to print “Hello!” 5 times:
console.log("Hello!");
console.log("Hello!");
console.log("Hello!");
console.log("Hello!");
console.log("Hello!");
This works, but it’s:
for (let i = 0; i < 5; i++) {
console.log("Hello!");
}
This prints “Hello!” 5 times — but the code is:
5
to any number)A loop is a programming tool that:
0
)i < 5
?)Step | What Happens |
---|---|
i = 0 | Check: Is i < 5? → Yes → Run code |
i = 1 | Check: Is i < 5? → Yes → Run code |
i = 2 | Yes → Run code |
i = 3 | Yes → Run code |
i = 4 | Yes → Run code |
i = 5 | No → Stop the loop |
You want to do 10 push-ups. Instead of:
You say:
“Repeat push-up 10 times”
That’s what a loop does in code.
Loops are powerful because they let you:
Use Case | Example |
---|---|
Repeat a task | Display a message multiple times |
Process a list | Go through all items in an array |
Automate behavior | Animate something on a website |
Search data | Find a value inside a dataset |
Validate input | Check every field in a form |
for (let i = 1; i <= 3; i++) {
console.log("This is loop number " + i);
}
Output:
This is loop number 1
This is loop number 2
This is loop number 3
for
, while
, do...while
) that we’ll explore next