2.5K Views

JS108 - Loops & Iteration

Learn how to repeat actions in JavaScript using for, while, do-while, for...of, and forEach loops to iterate through data.

Loops allow you to repeat actions and process lists of data efficiently.
JavaScript provides several loop types, each with different use cases.

for Loop

The classic for loop runs a block of code a specific number of times.

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

while Loop

Runs as long as the condition is true.

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

do-while Loop

Runs at least once even if the condition is false.

let x = 5;
 
do {
  console.log(x);
  x--;
} while (x > 0);

for...of Loop

Used for iterating over arrays or iterable objects.

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

forEach Method

A cleaner way to loop through arrays.

fruits.forEach(function(item) {
  console.log(item);
});

With arrow functions:

fruits.forEach(item => console.log(item));

Looping Through Objects

Objects are not directly iterable.
Use for...in to loop through keys.

let user = {
  name: "Emre",
  age: 30,
  city: "Antalya"
};
 
for (let key in user) {
  console.log(key + ": " + user[key]);
}

Breaking and Continuing Loops

for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i);
}

continue skips to the next iteration:

for (let i = 0; i < 5; i++) {
  if (i === 2) continue;
  console.log(i);
}

Infinite Loops (Avoid)

A loop runs forever if the condition never becomes false.

while (true) {
  // This never stops!
}

Always ensure loop conditions update correctly.


Summary

In this lesson, you learned:

  • for, while, and do-while loops
  • for...of and for...in
  • forEach array iteration
  • How to break and continue loops
  • How to avoid infinite loops

In the next lesson, we will learn DOM Manipulation — how JavaScript interacts with HTML elements.