Understanding Loops in JavaScript: Automating Repetitive Tasks
Learn how to use for, while, and do...while loops to write cleaner, more efficient JavaScript code

In the previous parts of the JavaScript Decoded series, we tackled how to store data and how to build reusable blocks of code using Functions. But what happens when you need to run the exact same block of code 10, 100, or even 1,000 times?
Imagine you are building an app that prints the lyrics to “99 Bottles of Milk on the Wall.” Typing console.log() 99 times would be a nightmare!
This is exactly where Loops come in.
Loops are one of the most powerful concepts in programming. They allow you to execute a block of code repeatedly until a specific condition is met, saving you time and keeping your code incredibly clean.
In this guide, you will learn:
What loops are and why they are essential
The classic
forloop (and its 3 crucial parts)The
whileloop (and how to avoid infinite loops!)The
do...whileloopThe
breakandcontinuekeywordsA sneak peek at looping through arrays
Let’s get looping! 🔄
1. The Classic for Loop
The for loop is the most common loop in JavaScript. You will use this loop when you know exactly how many times you want your code to run.
It might look a bit intimidating at first, but it follows a very strict, reliable structure.
Syntax Breakdown
A for loop requires three statements separated by semicolons ;:
for (initialization; condition; afterthought/update) {
// Code to be repeated goes here
}
Let's look at a real example where we count from 1 to 5.
for (let i = 1; i <= 5; i++) {
console.log("Count is: " + i);
}
// Output:
// Count is: 1
// Count is: 2
// Count is: 3
// Count is: 4
// Count is: 5
What exactly is happening here?
let i = 1(Initialization): We create a variablei(short for index or iterator) and set it to 1. This happens exactly once, before the loop even starts.i <= 5(Condition): Before every single loop, JavaScript checks this condition. If it istrue, the loop runs. If it isfalse, the loop stops and the code moves on.i++(Update): After the code inside the curly braces finishes running, this statement executes. Here, we add 1 toi. Then, the loop goes back to step 2 to check the condition again!
2. The while Loop
While the for loop is great when you know the exact number of iterations, the while loop is perfect for when you don't know how many times the loop needs to run. It just keeps running while a condition remains true.
Syntax Breakdown
while (condition is true) {
// Run this code
}
Let's rewrite our 1 to 5 counter using a while loop:
let count = 1; // Initialization happens outside
while (count <= 5) {
console.log("While loop count: " + count);
count++; // CRITICAL: You must update the variable inside the loop!
}
⚠️ Beware the Infinite Loop!
What happens if you forget to include count++ in the example above? The count will stay at 1 forever. Since 1 <= 5 will always be true, the loop will run infinitely, freeze your browser, and crash your program!
Always make sure the condition in a while loop will eventually become false.
3. The do...while Loop
The do...while loop is the quirky cousin of the while loop.
In a standard while loop, JavaScript checks the condition before running the code. If the condition is false from the very beginning, the code never runs.
A do...while loop is different: it executes the code block first, and then checks the condition. This guarantees that your code will run at least once, no matter what.
Syntax Breakdown
let number = 10;
do {
console.log("This will print at least once! Number is: " + number);
number++;
} while (number < 5);
// Output:
// "This will print at least once! Number is: 10"
Even though 10 < 5 is false, the text still prints once because the condition check happens at the very end!
Controlling the Chaos: break and continue
Sometimes, you need to micromanage your loop while it is running. JavaScript gives you two keywords to do this.
The break Statement
The break statement instantly "breaks out" of the loop entirely, stopping all future iterations.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
console.log("Hit 5! Breaking the loop early.");
break; // Loop stops completely here
}
console.log(i);
}
// Outputs: 1, 2, 3, 4, "Hit 5! Breaking the loop early."
The continue Statement
The continue statement is less aggressive. Instead of stopping the whole loop, it just skips the current iteration and instantly moves on to the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skips logging '3'
}
console.log(i);
}
// Outputs: 1, 2, 4, 5
A Sneak Peek: Looping Through Data
In the real world, you rarely use loops just to print numbers. You usually use loops to go through lists of data—like a list of users, products, or high scores.
In JavaScript, lists of data are called Arrays. Here is a sneak peek of how powerful a for loop is when combined with an array:
let favoriteColors = ["Red", "Blue", "Green", "Purple"];
// We start at index 0, and stop when we hit the length of the array!
for (let i = 0; i < favoriteColors.length; i++) {
console.log("A great color is: " + favoriteColors[i]);
}
We will dive deep into Arrays in Part 6 of this series, but now you understand the mechanical engine that makes reading lists of data possible!
Your Turn: Loop Assignments 💻
The only way to get comfortable with loops is to write them! Try these challenges in your code editor:
Write a
forloop that prints all even numbers between 2 and 20.Write a
whileloop that counts down from 10 to 1, and then prints "Blast off! 🚀".Add a
breakstatement to your blast-off loop so that if the countdown hits 5, the loop stops early and prints "Launch aborted!" instead.
What's Next?
Now that you know how to automate repetitive tasks, you are ready to learn how to store the complex lists of data that these loops were meant to iterate over!
Up next in the JavaScript Decoded series:
Arrays 101 — How to store and access ordered lists of data
Array Methods — Built-in tricks for managing arrays
Objects — Storing data using key-value pairs
Happy coding! 🎉





