JavaScript Iterables
JavaScript Basics

JavaScript Iterables

The For Of Loop

The JavaScript for...of statement loops through the elements of an iterable object.

Syntax

for (variable of iterable) {  // code block to be executed}

Iterating

Iterating means looping over a sequence of elements.

Examples

Iterating Over a String

You can use a for...of loop to iterate over the characters of a string:

const greeting = "HelloWorld";

for (const char of greeting) {  console.log(char);}

In this example, each character of the string greeting is logged to the console.

Iterating Over an Array

You can use a for...of loop to iterate over the elements of an array:

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

Example 2

const numbers = [1, 2, 3, 4, 5];‍for (const number of numbers) {  console.log(number);}

Iterating Over a Set

You can use a for...of loop to iterate over the elements of a Set:

const fruits = new Set(["apple", "banana", "cherry"]);‍for (const fruit of fruits) {  console.log(fruit);}

Iterating Over a Map

You can use a for...of loop to iterate over the elements of a Map:

const prices = new Map([  ["apple", 1.5],  ["banana", 1.0],  ["cherry", 2.0]]);‍for (const [fruit, price] of prices) {  console.log(`${fruit}: $${price}`);}

JavaScript Iterators

The iterator protocol defines how to produce a sequence of values from an object. An object becomes an iterator when it implements a next() method.

The next() method must return an object with two properties:

  • value: The next value in the sequence.
  • done: true if the sequence is complete, false otherwise.

Example: Homemade Iterable

This example shows a homemade iterable that produces an endless sequence of numbers increasing by 10 each time:

// Homemade Iterablefunction createNumbers() {  let n = 0;  return {    next() {      n += 10;      return { value: n, done: false };    }  };}‍// Create an Iterableconst numbers = createNumbers();console.log(numbers.next().value); // 10console.log(numbers.next().value); // 20console.log(numbers.next().value); // 30

Making an Object Iterable

To make an object iterable, it must implement the Symbol.iterator method, which returns an iterator object with a next() method.

Example

This example creates an object that can be iterated over using a for...of loop:

const myNumbers = {
  [Symbol.iterator]() {
    let n = 0;
    return {
      next() {
        n += 10;
        if (n > 50) {
          return { value: undefined, done: true };
        }
        return { value: n, done: false };
      }
    };
  }
};

for (const num of myNumbers) {
  console.log(num); // 10, 20, 30, 40, 50
}

The Symbol.iterator method is called automatically by for...of, but you can also call it manually:

const iterator = myNumbers[Symbol.iterator]();

let result = iterator.next();
while (!result.done) {
  console.log(result.value);
  result = iterator.next();
}

Take a look into your desired course