Loops: Repeating Actions in JavaScript


Welcome to post 5 of JavaScript Mastery series. In the previous post, we looked into a Control flow topic - Conditionals - if
, else
, if..else if..else
, etc. In this, we will look into one of the most common Control Flow topics, Loops!
Loops allow you to repeat code multiple times without writing it over and over. They're perfect for tasks like processing lists, creating patterns, or repeating actions until a condition is met.
Types of Loops in JavaScript
In JavaScript, there are multiple loops which can be used based on the situation you are presented with. Let’s look at all of them one by one:
The for
Loop
The for
loop is perfect when you know how many times you want to repeat something:
/* SYNTAX
for (<initialization>; <exit condition>; <looping logic>) {
<task to execute repeatedly>
}
*/
// Print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(`Number: ${i}`);
}
// Output:
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5
The for
loop has three parts:
Initialization (
let i = 1
) - runs once at the startExit Condition (
i <= 5
) - checked before each iterationUpdate (
i++
) - runs after each iteration
The for..of
Loop
One of the most common uses of loops is processing arrays and for this, you can use a much simpler form of for
loop, also known as for..of
loop.
A short video: https://youtube.com/shorts/EB5M4z19TOo?si=2g6KH8SAC36XV7vx
let fruits = ["apple", "banana", "orange", "grape"];
// Using a traditional for loop
for (let i = 0; i < fruits.length; i++) {
console.log(`Fruit ${i + 1}: ${fruits[i]}`);
}
// Using for...of loop (cleaner for arrays)
for (let fruit of fruits) {
console.log(`I like ${fruit}s!`);
}
The for..in
Loop
The for..in
loop looks very similar to the for..of
loop, but instead of iterating over the values, it iterates over the keys. So, it is very useful in iterating over properties of objects.
A short video: https://youtube.com/shorts/BMdy5aEArS4?si=raezwXG-jzzU6Zks
let person = {
name: "Shubhaw",
company: "Microsoft",
blog: "JavaScript Mastery"
}
for (let prop in person) {
console.log(`My ${prop} is ${person[prop]}`);
}
// Output:
// My name is Shubhaw
// My company is Microsoft
// My blog is JavaScript Mastery
The while
Loop
Use while
when you want to repeat something until a condition becomes false:
let countdown = 5;
while (countdown > 0) {
console.log(`Countdown: ${countdown}`);
countdown--; // Important: update the condition variable!
}
console.log("Blast off! 🚀");
Warning: Make sure your condition will eventually become false, otherwise you'll create an infinite loop, which will ultimately crash your program!
The do...while
Loop
Similar to while
, but the code runs at least once before checking the condition:
let userInput;
do {
userInput = prompt("Enter a number greater than 10:");
} while (userInput <= 10);
console.log("Thank you!");
Real-World Examples
Let's look at some practical examples that combine conditionals and loops:
Example 1: Shopping Cart Calculator
let shoppingCart = [
{ name: "T-shirt", price: 20, quantity: 2 },
{ name: "Jeans", price: 50, quantity: 1 },
{ name: "Sneakers", price: 80, quantity: 1 }
];
let total = 0;
let itemCount = 0;
// Calculate total cost and item count
for (let item of shoppingCart) {
let itemTotal = item.price * item.quantity;
total += itemTotal;
itemCount += item.quantity;
console.log(`${item.name}: $${item.price} x ${item.quantity} = $${itemTotal}`);
}
// Apply discount for large orders
let discount = 0;
if (total > 100) {
discount = total * 0.1; // 10% discount
console.log(`Discount applied: $${discount.toFixed(2)}`);
}
let finalTotal = total - discount;
console.log(`Order Summary:`);
console.log(`Items: ${itemCount}`);
console.log(`Subtotal: $${total.toFixed(2)}`);
console.log(`Final Total: $${finalTotal.toFixed(2)}`);
Example 2: Simple Number Guessing Game
function numberGuessingGame() {
let attempts = 0;
const maxAttempts = 7;
let hasWon = false;
console.log("Welcome to the Number Guessing Game!");
console.log("I'm thinking of a number between 1 and 100.");
const targetNumber = Math.floor(Math.random() * 100) + 1; // Random number 1-100
while (attempts < maxAttempts && !hasWon) {
let guess = parseInt(prompt(`Attempt ${attempts + 1}/${maxAttempts}: Enter your guess:`));
attempts++;
if (guess === targetNumber) {
hasWon = true;
console.log(`🎉 Congratulations! You guessed it in ${attempts} attempts!`);
} else if (guess < targetNumber) {
console.log("Too low! Try a higher number.");
} else {
console.log("Too high! Try a lower number.");
}
}
if (!hasWon) {
console.log(`😢 Game over! The number was ${targetNumber}.`);
}
}
// Uncomment to play (works in browser console)
// numberGuessingGame();
Loop Control Statements
Sometimes you need more control over how loops execute:
break
- Exit the Loop
// Find the first even number in an array
let numbers = [1, 3, 7, 8, 9, 12];
for (let number of numbers) {
if (number % 2 === 0) {
console.log(`First even number found: ${number}`);
break; // Exit the loop immediately
}
}
continue
- Skip to Next Iteration
// Print only odd numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // Only prints 1, 3, 5, 7, 9
}
Common Mistakes to Avoid
1. Infinite Loops
// ❌ This will run forever!
let i = 0;
while (i < 10) {
console.log(i);
// Forgot to increment i!
}
// ✅ Correct version
let i = 0;
while (i < 10) {
console.log(i);
i++; // Don't forget to update the condition variable!
}
2. Off-by-One Errors
let fruits = ["apple", "banana", "orange"];
// ❌ This will cause an error (index out of bounds)
for (let i = 0; i <= fruits.length; i++) {
console.log(fruits[i]);
}
// ✅ Correct version
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Try It Yourself!
Here's a challenge to practice what you've learned:
Challenge: Create a simple grade calculator
Write a program that:
Takes an array of test scores
Calculates the average
Determines the letter grade (A, B, C, D, F)
Counts how many scores are above average
Lists all failing scores (below 60)
// Starter code
let testScores = [85, 92, 78, 96, 45, 88, 73];
// Your code here!
What's Next?
In our next blog post, we'll dive into functions—one of the most important concepts in JavaScript. Functions allow you to organize your code into reusable blocks, making your programs more efficient and easier to maintain.
Share your solutions to the challenge in the comments below! And let me know which of the above Loop did you like the most?
Subscribe to my newsletter
Read articles from Shubhaw Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Shubhaw Kumar
Shubhaw Kumar
Software Engineer at Microsoft, India