Loops in JavaScript

ADVERTISEMENT

Why Use Loops?

Loops let you run the same block of code multiple times—great for repeating tasks like processing items in a list, checking conditions, or building dynamic output.

for Loop

The for loop is best when you know exactly how many times you want to repeat something.

Syntax:

for (initialization; condition; update) {
  // code to run each loop
}

Example:

for (let i = 1; i <= 5; i++) {
  console.log("Step", i);
}

Output:

Step 1
Step 2
Step 3
Step 4
Step 5

while Loop

Use while when you want to repeat something as long as a condition is true.

Syntax:

while (condition) {
  // code
}

Example:

jsCopyEditlet count = 1;

while (count <= 3) {
  console.log("Count:", count);
  count++;
}

do…while Loop

A do...while loop is similar to while, but it runs at least once, even if the condition is false at the start.

Syntax:

do {
  // code
} while (condition);

Example:

let num = 1;

do {
  console.log("Number:", num);
  num++;
} while (num <= 2);

break and continue

break

Exits the loop completely when a certain condition is met.

for (let i = 1; i <= 5; i++) {
  if (i === 3) break;
  console.log(i);
}
// Output: 1 2

continue

Skips the current loop iteration and moves to the next one.

for (let i = 1; i <= 5; i++) {
  if (i === 3) continue;
  console.log(i);
}
// Output: 1 2 4 5

Looping Through Arrays

You’ll often loop over arrays to access their items.

Example with for:

let fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

for…in vs for…of

Both are used to loop over collections, but they work differently.

for…in

  • Loops over keys or indexes
  • Use for objects or array indices
let student = { name: "Alice", age: 22 };

for (let key in student) {
  console.log(key, ":", student[key]);
}

for…of

  • Loops over values
  • Works with arrays, strings, maps, sets
let colors = ["red", "green", "blue"];

for (let color of colors) {
  console.log(color);
}

Summary

  • Use for when you know the number of repetitions.
  • Use while for condition-based looping.
  • Use do...while when the loop should run at least once.
  • break exits the loop early; continue skips to the next iteration.
  • Use for...in for object properties, and for...of for values in arrays or iterable items.

ADVERTISEMENT