JavaScript : Iterables

In JavaScript, an iterable is an object that implements the iterable protocol, allowing it to be iterated over using the for...of  loop or other looping mechanisms that work with iterables. Iterables provide a way to access their elements sequentially, one at a time. 

An object is considered iterable if it has a special method named Symbol.iterator , which returns an iterator object with a next() method. The next() method returns an object with two properties: value, representing the next element in the iteration, and done , indicating whether the end of the iterable has been reached.

Example of Iterable (Array):


const iterableArray = ['a', 'b', 'c'];

// Using for...of loop to iterate over the array
for (let item of iterableArray) {
  console.log(item);
}

 

Example of Iterable (String):


const iterableString = 'Hello';

// Using for...of loop to iterate over the characters in the string
for (let char of iterableString) {
  console.log(char);
}

 

Custom Iterable Object:


You can also create custom iterable objects by implementing the iterable protocol. Here's an example:


const customIterableObject = {
  data: [1, 2, 3, 4],
  [Symbol.iterator]: function() {
    let index = 0;
    return {
      next: () => {
        return index < this.data.length ?
          { value: this.data[index++], done: false } :
          { done: true };
      }
    };
  }
};

// Using for...of loop to iterate over the custom iterable object
for (let item of customIterableObject) {
  console.log(item);
}

 

Output:

1
2
3
4

 

In this example, customIterableObject is a custom iterable object that implements the iterable protocol by defining a Symbol.iterator method that returns an iterator object with a next() method.

Iterables are fundamental in JavaScript for working with collections of data, enabling iteration over arrays, strings, maps, sets, and custom iterable objects. They provide a convenient way to access elements sequentially, making your code more expressive and readable.