When I started learning JavaScript, I often repeated the same code multiple times. Then I learned about loops, which made my code much easier to write!
What is a Loop?
A loop allows us to execute a block of code repeatedly while a condition is satisfied.
For example, instead of writing console.log() five times, we can use a loop to print numbers from 1 to 5.
- For Loop
A for loop is useful when we want to repeat something a specific number of times.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
How does it work?
let i = 1 → Starts the counter at 1.
i <= 5 → Checks the condition.
i++ → Increases the counter by 1.
The loop stops when the condition becomes false.
- While Loop
A while loop repeats code as long as its condition is true.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
It produces the same output as the for loop.
Important: Remember to update the counter. Otherwise, the loop might run forever!
- Do-While Loop
A do...while loop executes the code at least once, even if the condition is false.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
For Loop vs While Loop
For Loop
While Loop
Useful when the number of repetitions is known
Useful when repetition depends on a condition
Initialization, condition, and update are together
These are usually written separately
Common for counting and arrays
Common for condition-based tasks
- Using a Loop with an Array
Loops are especially useful when working with arrays.
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
Apple
Banana
Mango
Here, fruits.length tells us how many elements are in the array.
Where Are Loops Used?
Displaying product lists
Processing student records
Calculating totals
Searching for values
Repeating tasks automatically
Conclusion
Loops are one of the most important JavaScript fundamentals. Start with the for loop, understand the condition and counter, and then practice while and do...while.
Learn → Practice → Build → Improve! 🚀
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.