Skip to main content

Archive

Show more

JavaScript Iterables

JavaScript Iterables

In JavaScript, iterables are objects that allow you to iterate over their elements. They are a fundamental concept in modern JavaScript, enabling you to work with data structures such as arrays, strings, and maps in a consistent way. Understanding iterables and how to use them can simplify your code and improve its efficiency.


What is an Iterable?

An iterable is an object that implements the Symbol.iterator method. This method returns an iterator, which is an object with a next method that returns the next value in the sequence. Iterables are used by various JavaScript constructs such as loops and the spread operator to access their elements.


Creating an Iterable

To create a custom iterable, you need to define the Symbol.iterator method in your object. Here’s a basic example:

const iterableObject = {
  items: [1, 2, 3],
  
  [Symbol.iterator]() {
    let index = 0;
    const items = this.items;
    
    return {
      next() {
        if (index < items.length) {
          return { value: items[index++], done: false };
        } else {
          return { value: undefined, done: true };
        }
      }
    };
  }
};

for (const item of iterableObject) {
  console.log(item);
}
// Output:
// 1
// 2
// 3
  • The object iterableObject implements the Symbol.iterator method.
  • The iterator object returned by Symbol.iterator has a next method that yields items one by one.
  • The for...of loop iterates over the items of iterableObject.

Using Built-in Iterables

Many built-in JavaScript objects are iterables, including:

  • Array
  • String
  • Map
  • Set

Here’s an example of using a built-in iterable, such as an array:

const numbers = [10, 20, 30];

for (const number of numbers) {
  console.log(number);
}
// Output:
// 10
// 20
// 30
  • The array numbers is iterable by default.
  • The for...of loop iterates over each element of the array.

Understanding Iterators

An iterator is an object with a next method that returns an object with two properties:

  • value: The next value in the sequence.
  • done: A boolean indicating if the iterator is finished.

Here’s an example of creating an iterator manually:

const array = [1, 2, 3];
const iterator = array[Symbol.iterator]();

console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
  • The iterator object is obtained from the array's Symbol.iterator method.
  • Each call to iterator.next() returns the next value in the sequence until done is true.

Iterables with forEach

The forEach method can also be used with iterable objects to execute a provided function once for each element. Here’s an example:

const fruits = ['apple', 'banana', 'cherry'];

fruits.forEach(fruit => {
  console.log(fruit);
});
// Output:
// apple
// banana
// cherry
  • The forEach method iterates over the elements of the fruits array.
  • The provided function is executed for each element.

Conclusion

Iterables in JavaScript are powerful tools that provide a uniform way to access and work with elements in various data structures. By implementing the Symbol.iterator method, you can create custom iterables and work with built-in iterables effectively. Understanding iterables and iterators enhances your ability to handle and manipulate data efficiently in JavaScript.

Comments