In the previous tutorial, you learned how to make decisions with if, else and switch. Now imagine you want to print “Hello” 100 times. Would you write console.log("Hello") 100 times? Of course not. This is where JavaScript Loops help you. They repeat a block of code again and again, so you write it only once.
Why Do We Need Loops?
Look at this code without a loop:
console.log("Number 1");
console.log("Number 2");
console.log("Number 3");
console.log("Number 4");
console.log("Number 5");
Now look at the same result with a loop:
for (let i = 1; i <= 5; i++) {
console.log("Number " + i);
}
Same output, only 3 lines. If you need 1000 numbers, you just change 5 to 1000. That is the power of JavaScript Loops.
1. The for Loop
The for loop is used when you know how many times you want to repeat something.
// Syntax
// for (start; condition; step) {
// code to repeat
// }
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output: 1 2 3 4 5 (each on a new line). Let us understand the 3 parts inside the brackets:
let i = 1is the start. It runs only once, at the beginning.i <= 5is the condition. The loop continues while this is true.i++is the step. It runs after every round and increases i by 1.
How it runs step by step
| Round | Value of i | i <= 5 ? | Action |
|---|---|---|---|
| 1 | 1 | true | print 1, then i becomes 2 |
| 2 | 2 | true | print 2, then i becomes 3 |
| 3 | 3 | true | print 3, then i becomes 4 |
| 4 | 4 | true | print 4, then i becomes 5 |
| 5 | 5 | true | print 5, then i becomes 6 |
| 6 | 6 | false | loop stops |
More for loop examples
// Count backwards
for (let i = 5; i >= 1; i--) {
console.log(i);
}
console.log("Go!");
// Print even numbers from 2 to 10
for (let i = 2; i <= 10; i += 2) {
console.log(i);
}
// Multiplication table of 5
for (let i = 1; i <= 10; i++) {
console.log("5 x " + i + " = " + (5 * i));
}
// Sum of numbers 1 to 100
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log("Sum: " + sum); // Sum: 5050
2. The while Loop
The while loop is used when you do not know exactly how many times it will run. It keeps running as long as the condition is true.
// Syntax
// while (condition) {
// code to repeat
// }
let count = 1;
while (count <= 5) {
console.log("Count: " + count);
count++;
}
Warning: if you forget count++, the condition will always stay true and the loop will never stop. This is called an infinite loop and it can freeze your browser tab.
// Real example: save money until goal is reached
let savings = 0;
let goal = 1000;
let months = 0;
while (savings < goal) {
savings += 150;
months++;
}
console.log("It takes " + months + " months to save " + goal);
// It takes 7 months to save 1000
3. The do…while Loop
The do...while loop runs the code at least one time, and then checks the condition. In a normal while loop, the condition is checked first.
// Syntax
// do {
// code to repeat
// } while (condition);
let number = 1;
do {
console.log("Number: " + number);
number++;
} while (number <= 3);
The difference: while vs do…while
let x = 10;
while (x < 5) {
console.log("while: runs"); // never prints
}
do {
console.log("do-while: runs"); // prints one time
} while (x < 5);
Here the condition x < 5 is false from the start. The while loop does not run at all, but do...while runs once. Use it for things like menus, where you must show the menu at least one time.
4. The for…of Loop
The for...of loop is the easiest way to go through every item of an array (or a string).
let fruits = ["Apple", "Banana", "Mango", "Orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// Looping through a string
let word = "Hello";
for (let letter of word) {
console.log(letter);
}
Same task with a normal for loop
let fruits = ["Apple", "Banana", "Mango", "Orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(i + ": " + fruits[i]);
}
Use the normal for loop when you need the index number (0, 1, 2…). Use for...of when you only need the values.
5. The for…in Loop
The for...in loop goes through the keys (property names) of an object.
let student = {
name: "Ayesha",
age: 22,
city: "Karachi"
};
for (let key in student) {
console.log(key + ": " + student[key]);
}
// Output:
// name: Ayesha
// age: 22
// city: Karachi
Remember: for...of is for arrays and strings (values), and for...in is for objects (keys).
break and continue
These two keywords give you more control inside JavaScript Loops.
break: stop the loop completely
for (let i = 1; i <= 10; i++) {
if (i === 6) {
break;
}
console.log(i);
}
// Output: 1 2 3 4 5
continue: skip this round only
for (let i = 1; i <= 6; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
// Output: 1 2 4 5 6 (3 is skipped)
Nested Loops (Loop Inside a Loop)
You can put one loop inside another. The inner loop completes fully for every single round of the outer loop.
for (let row = 1; row <= 3; row++) {
for (let col = 1; col <= 3; col++) {
console.log("Row " + row + ", Col " + col);
}
}
// Star pattern
let stars = "";
for (let i = 1; i <= 5; i++) {
stars = "";
for (let j = 1; j <= i; j++) {
stars += "* ";
}
console.log(stars);
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
Practical Example 1: Sum of Array Numbers
let marks = [85, 90, 78, 92, 66];
let total = 0;
for (let mark of marks) {
total += mark;
}
let average = total / marks.length;
console.log("Total: " + total); // Total: 411
console.log("Average: " + average); // Average: 82.2
Practical Example 2: Find the Highest Number
let numbers = [12, 45, 7, 89, 34, 56];
let highest = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > highest) {
highest = numbers[i];
}
}
console.log("Highest number: " + highest); // 89
Practical Example 3: FizzBuzz (Famous Interview Question)
for (let i = 1; i <= 15; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
This small program uses loops, operators and conditional statements together. Many companies ask this question in job interviews, so practice it well.
Practical Example 4: Show a List on a Webpage
<ul id="list"></ul>
<script>
let courses = ["HTML", "CSS", "PHP", "JavaScript"];
let output = "";
for (let course of courses) {
output += "<li>" + course + "</li>";
}
document.getElementById("list").innerHTML = output;
</script>
Do not worry about document.getElementById right now. We will cover the DOM in detail later in this series.
Which Loop Should You Use?
| Loop | Best used when |
|---|---|
| for | You know how many times to repeat |
| while | You do not know how many times, condition decides |
| do…while | Code must run at least once |
| for…of | You want every value of an array or string |
| for…in | You want every key of an object |
Common Mistakes to Avoid
// Mistake 1: infinite loop (forgot to change the counter)
// let i = 1;
// while (i <= 5) {
// console.log(i);
// }
// Mistake 2: off-by-one error with arrays
let items = ["a", "b", "c"];
// for (let i = 0; i <= items.length; i++) WRONG: last round gives undefined
for (let i = 0; i < items.length; i++) { // CORRECT
console.log(items[i]);
}
// Mistake 3: using for...in on arrays (use for...of instead)
Quick Recap
forloop: best when you know the number of roundswhileloop: runs while the condition is truedo...whileloop: runs at least oncefor...ofloop: values of arrays and stringsfor...inloop: keys of objectsbreakstops the loop,continueskips one round
Excellent! You can now repeat tasks easily using JavaScript Loops. Loops are used in almost every real application, from showing product lists to processing form data.
Practice Exercises
- Print numbers from 1 to 20 using a
forloop. - Print all odd numbers between 1 and 30.
- Print the multiplication table of any number you like (1 to 10).
- Use a
whileloop to print numbers from 10 down to 1. - Create an array of 5 city names and print each one using
for...of. - Calculate the factorial of 5 (5 x 4 x 3 x 2 x 1 = 120) using a loop.
- Print only the numbers from 1 to 20 that are divisible by 3, using
continueto skip the others. - Create an object with 4 properties of a book (title, author, price, year) and print every key and value using
for...in.
Assignment
Build a Student Marks Report:
- Create an array of 6 student marks, for example
[78, 45, 92, 33, 67, 88]. - Use a loop to calculate the total and average.
- Use a loop to find the highest and lowest marks.
- Use a loop with
if...elseto count how many students passed (40 or above) and how many failed. - Print the final report like this:
Total Students: 6
Total Marks: 403
Average: 67.17
Highest: 92
Lowest: 33
Passed: 5
Failed: 1
Bonus Challenge
Print this number pyramid using nested loops:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Extra bonus: write a program that prints all prime numbers between 1 and 50.
What’s Next?
In the next tutorial, we will learn JavaScript Functions. Functions let you put your code into reusable blocks, so you can run it any time with just one line. You will also combine functions with the JavaScript Loops you learned today.
Missed the last tutorial? Go back to JavaScript Conditional Statements, or browse the full JavaScript Tutorial Series. For deeper reference, see the MDN guide to loops and iteration.

