NelsonLabs

Loops

Loops repeat code until a condition is no longer true. They're fundamental to processing lists, generating content, and building any kind of repetitive logic.

The for loop
javascript
// for (initialise; condition; update)
for (let i = 0; i < 5; i++) {
  console.log(i);
}
// 0, 1, 2, 3, 4

// Loop through an array by index
const courses = ["HTML", "CSS", "JavaScript"];
for (let i = 0; i < courses.length; i++) {
  console.log(`${i + 1}. ${courses[i]}`);
}
// 1. HTML  2. CSS  3. JavaScript
for...of — the cleaner way to iterate arrays
javascript
const courses = ["HTML", "CSS", "JavaScript", "React"];

// Cleaner than a for loop when you don't need the index
for (const course of courses) {
  console.log(course);
}
// HTML, CSS, JavaScript, React

// Works on strings too
for (const char of "hello") {
  console.log(char);
}
// h, e, l, l, o
while and do...while
javascript
// while — check condition BEFORE each iteration
let count = 0;
while (count < 3) {
  console.log("count is", count);
  count++;
}

// do...while — runs at LEAST ONCE, checks condition after
let input;
do {
  input = prompt("Enter a number greater than 10:");
} while (Number(input) <= 10);
break and continue
javascript
// break — exit the loop entirely
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i);
}
// 0, 1, 2, 3, 4  (stops at 5)

// continue — skip the current iteration
for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) continue;  // skip even numbers
  console.log(i);
}
// 1, 3, 5, 7, 9