Loop
In one line
A loop is a construct that repeats a block of code multiple times, either a fixed number or until a condition is met.
In simple words
A loop lets you run the same block of code over and over without copying and pasting it. This is essential when you need to process every item in an array, repeat a calculation, or keep asking for input until the user gives a valid answer.
The two most common kinds are the for loop (repeat a known number of times) and the while loop (repeat until a condition becomes false). Most languages also offer a for...of or foreach loop that walks through each element of a collection directly.
The danger with loops is the infinite loop — if the stopping condition is never met, the loop runs forever and freezes your program. Always make sure the loop can exit.
Example
// for loop — repeat 5 times
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// while loop — repeat until condition is false
let count = 3;
while (count > 0) {
console.log(count); // 3, 2, 1
count--;
}A for loop runs a fixed number of times. A while loop runs until its condition becomes false.
Common confusions
Confused with: recursion
The difference: A loop repeats code using iteration (for/while); recursion repeats by a function calling itself. Loops are usually more efficient; recursion can be clearer for tree-structured problems.
Related terms
Related Resources
Related Lessons
- Loops
Learn for, while, and for...of loops
Learn the fundamentals
Deepen your understanding with structured lessons on this topic.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.