JS Iterations

Iteration methods simplify working with collections. Explore forEach, map, filter, reduce, and more.

On this page

JS Iterations

Iteration means going through items one by one. JavaScript supports classic loops, modern iterable protocols, iterators, and generators.

JS Loops

Classic loops are the most direct way to iterate.

for (let i = 0; i < 3; i++) {
  console.log(i);
}

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

Modern tip: for arrays, prefer for...of or array iteration methods when it improves readability.

const nums = [10, 20, 30];

for (const value of nums) {
  console.log(value);
}

Use for...in for object keys (not arrays).

const user = { name: "Ozan", age: 30 };

for (const key in user) {
  console.log(key, user[key]);
}

Modern Array Iteration Methods

These methods are used constantly in modern JavaScript.

const values = [1, 2, 3, 4];

const doubled = values.map(v => v * 2);
const big = values.filter(v => v > 2);
const sum = values.reduce((acc, v) => acc + v, 0);

console.log(doubled); // [2,4,6,8]
console.log(big);     // [3,4]
console.log(sum);     // 10

JS Iterables

An iterable is an object that can be iterated with for...of. Common iterables: arrays, strings, sets, maps.

const text = "JS";
for (const ch of text) {
  console.log(ch);
}

Maps are iterables of [key, value] pairs.

const m = new Map([
  ["a", 1],
  ["b", 2]
]);

for (const [k, v] of m) {
  console.log(k, v);
}

You can also iterate keys or values explicitly.

for (const k of m.keys()) {
  console.log("key:", k);
}

for (const v of m.values()) {
  console.log("value:", v);
}

JS Iterators

An iterator is an object with a next() method that returns { value, done }.

const arr = [10, 20, 30];
const it = arr[Symbol.iterator]();

console.log(it.next()); // { value: 10, done: false }
console.log(it.next()); // { value: 20, done: false }
console.log(it.next()); // { value: 30, done: false }
console.log(it.next()); // { value: undefined, done: true }

You can create your own iterable by implementing Symbol.iterator.

const range = {
  from: 1,
  to: 3,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;

    return {
      next() {
        if (current <= last) {
          return { value: current++, done: false };
        }
        return { value: undefined, done: true };
      }
    };
  }
};

for (const n of range) {
  console.log(n);
}

JS Generators

Generators are functions that can pause and resume. They use function* and yield to produce values lazily.

function* gen() {
  yield 1;
  yield 2;
  yield 3;
}

for (const v of gen()) {
  console.log(v);
}

Generators are great for building lazy sequences (values computed on demand).

function* counter(limit) {
  let n = 1;
  while (n <= limit) {
    yield n++;
  }
}

for (const n of counter(5)) {
  console.log(n);
}

Next Step

Continue with JS Math to learn common math operations and utility functions.

JS Iterations Examples (8)