Skip to main content

Skillber v1.0 is here!

Learn more

Loops & Iteration

Checking access...

Loops execute a block of code multiple times. They’re essential for working with arrays, processing data, and repeating tasks.

The for Loop

The classic loop — runs a block a specific number of times:

// Syntax: for (initialization; condition; increment)
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`);
}
// Output:
// Iteration 0
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4

How it works:

  1. let i = 0 — runs once at the start
  2. i < 5 — checked before each iteration
  3. Body executes if condition is true
  4. i++ — runs after each iteration
  5. Repeat from step 2

Looping Through Arrays

const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i}: ${fruits[i]}`);
}
// Output:
// 0: apple
// 1: banana
// 2: cherry

Backwards Loop

for (let i = fruits.length - 1; i >= 0; i--) {
console.log(fruits[i]);
}
// Output:
// cherry
// banana
// apple

The while Loop

Runs while a condition is true — useful when you don’t know the iteration count in advance:

let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// 0, 1, 2, 3, 4

while with a Flag

let found = false;
let attempts = 0;
while (!found && attempts < 10) {
attempts++;
// Simulate searching
if (Math.random() > 0.7) {
found = true;
console.log(`Found after ${attempts} attempts`);
}
}
if (!found) {
console.log("Not found after 10 attempts");
}

The do…while Loop

Always runs at least once — condition is checked after the body:

let input;
do {
input = prompt("Enter a number (or 'quit' to exit):");
console.log(`You entered: ${input}`);
} while (input !== "quit");

The for…of Loop (ES6)

Iterates over values of an iterable (arrays, strings, maps, sets):

const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
// red, green, blue
// Can use let for the variable if you need to reassign
for (let item of colors) {
item = item.toUpperCase();
console.log(item);
// RED, GREEN, BLUE
}
// Works with strings too
for (const char of "hello") {
console.log(char);
}
// h, e, l, l, o

The for…in Loop

Iterates over keys (properties) of an object:

const person = {
name: "Alice",
age: 30,
city: "New York"
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// name: Alice
// age: 30
// city: New York

Caution

Don’t use for...in with arrays — it iterates over keys (which are strings “0”, “1”, “2”) and may include prototype properties. Use for...of or a standard for loop for arrays.

break and continue

break — Exit the Loop

for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Stop the loop entirely
}
console.log(i);
}
// 0, 1, 2, 3, 4
// Practical: find first match
const numbers = [3, 7, 12, 5, 9, 15];
let firstMatch;
for (const num of numbers) {
if (num > 10) {
firstMatch = num;
break; // Stop searching once found
}
}
console.log(firstMatch); // => 12

continue — Skip to Next Iteration

for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}
// 1, 3, 5, 7, 9
// Practical: process only valid items
const items = [1, null, 3, undefined, 5, null, 7];
for (const item of items) {
if (item === null || item === undefined) {
continue;
}
console.log(item * 2);
}
// 2, 6, 10, 14

Nested Loops

Loops inside loops create combinations:

// Multiplication table (1-3)
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} × ${j} = ${i * j}`);
}
}
// 1 × 1 = 1
// 1 × 2 = 2
// 1 × 3 = 3
// 2 × 1 = 2
// ...etc

Loop Performance Tips

// ❌ Bad: recalculates length on every iteration
for (let i = 0; i < arr.length; i++) { ... }
// ✅ Good: cache length
for (let i = 0, len = arr.length; i < len; i++) { ... }
// ✅ Even better: for...of is usually optimized
for (const item of arr) { ... }

Which Loop to Use

LoopWhen to Use
forKnown iteration count, need index
for...ofIterating over array/string values (preferred for arrays)
for...inIterating over object keys
whileUnknown iteration count, condition-based
do...whileMust run at least once

Try It Yourself

// 1. Sum all numbers from 1 to 100 using a for loop
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(sum); // => 5050
// 2. Find the largest number in an array
const nums = [12, 45, 7, 89, 23, 56];
let max = nums[0];
for (const num of nums) {
// Your code here
}
// 3. Count how many vowels in a string
const text = "hello world";
let vowelCount = 0;
// Your code here
// 4. Print a triangle pattern
// *
// **
// ***
// ****
// *****

Key Takeaways

  • for loops have three parts: initialization, condition, increment
  • for...of is the cleanest way to iterate over arrays
  • for...in iterates object keys — don’t use it for arrays
  • while loops run while a condition is true; do...while always runs at least once
  • break exits the loop entirely; continue skips to the next iteration
  • Use break to stop searching after finding a match
  • Cache array.length in performance-sensitive for loops
  • Nested loops create combinations — be aware of O(n²) performance