Classic JS Tutorial | JS in VS 2026 | JS Examples | jQuery
⚡ Lesson 10 of 30

Loops – for, while, forEach

Iterate with classic for loops, while loops, for...of, for...in, and array iteration methods.

Classic for Loop

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

// Count down
for (let i = 5; i > 0; i--) {
  console.log(i); // 5 4 3 2 1
}

while & do...while

let n = 1;
while (n <= 5) {
  console.log(n++);
}

// do...while runs at least once
let x = 10;
do {
  console.log(x);
  x++;
} while (x < 10); // prints 10 once

for...of (Arrays & Iterables)

const colors = ["red","green","blue"];
for (const color of colors) {
  console.log(color);
}

// Works on strings too
for (const ch of "Hi!") {
  console.log(ch); // H i !
}

for...in (Object Keys)

const config = { host:"localhost", port:3000 };
for (const key in config) {
  console.log(`${key}: ${config[key]}`);
}

forEach, every, some

const nums = [1, 2, 3, 4, 5];
nums.forEach(n => console.log(n * 2));

const allPositive = nums.every(n => n > 0);  // true
const hasEven     = nums.some(n => n % 2 === 0); // true
← Lesson 09🏠 HomeLesson 11 →