JavaScript Loops

Learn how to use loops in JavaScript to execute code repeatedly.

Introduction to Loops

Loops allow you to run the same block of code multiple times with different values. Making your program more efficient and concise.

For Loop:

Executes a block of code a specific number of times:


for (let i = 0; i < 5; i++) {
  console.log("Iteration " + i);
}
            

While Loop:

Executes as long as a condition is true:


let i = 0;
while (i < 5) {
  console.log("i is " + i);
  i++;
}
            

Do-While Loop:

Executes at least once before checking the condition:


let i = 0;
do {
  console.log("Running once even if false");
  i++;
} while (i < 1);
            

for...of Loop

Used to loop through elements in iterable objects like arrays:


let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
  console.log(fruit);
}
            

break & continue

  • break – Exits the loop early
  • continue – Skips the current iteration

for (let i = 1; i <= 5; i++) {
  if (i === 3) continue; // skip 3
  if (i === 5) break;    // stop at 5
  console.log(i);
}
            

Practice Task

Print the even numbers from 1 to 10 using a loop:


for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    console.log(i);
  }
}