DEV Community

김영민
김영민

Posted on

Mastering JavaScript Iterables

Introduction to JavaScript Iterable Objects

Iterable objects in JavaScript represent a sequence of values that can be iterated over, such as arrays or strings. Understanding iterable objects is essential for effective data processing and manipulation in JavaScript.

What are Iterable Objects?

An iterable object is an object that implements the Symbol.iterator property, which returns an iterator. This iterator is responsible for yielding values one at a time, allowing us to iterate over the object's values using a for...of loop.

Structure of Iterable Objects

An iterable object consists of two main components:

  • Iterable: An object that defines the Symbol.iterator method, which returns an iterator.
  • Iterator: An object that has a next() method, which returns an object with value and done properties.
let arr = [1, 2, 3, 4, 5];

for (let value of arr) {
  console.log(value);  // 1, 2, 3, 4, 5
}
Enter fullscreen mode Exit fullscreen mode

Examples of Iterable Objects

Some of the most commonly used iterable objects include:

  • Arrays: Can be iterated over using for...of to access each element.
  • Strings: Can be iterated over character by character.
let str = "Hello";

for (let char of str) {
  console.log(char);  // 'H', 'e', 'l', 'l', 'o'
}
Enter fullscreen mode Exit fullscreen mode

Implementing Custom Iterable Objects

We can create our own iterable objects by defining the Symbol.iterator method and implementing the iterator logic.

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

for (let value of myIterable) {
  console.log(value);  // 1, 2, 3, 4, 5
}
Enter fullscreen mode Exit fullscreen mode

Differences Between for...of and for...in

  • for...of: Iterates over the values of an iterable object.
  • for...in: Iterates over the keys of an object.
let arr = [10, 20, 30];

// for...of iterates over values
for (let value of arr) {
  console.log(value);  // 10, 20, 30
}

// for...in iterates over indices
for (let index in arr) {
  console.log(index);  // 0, 1, 2
}
Enter fullscreen mode Exit fullscreen mode

Using the Spread Operator with Iterable Objects

The spread operator (...) can be used to expand an iterable object into an array or another iterable.

let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];  // expands the array and creates a new one
console.log(newArr);  // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Examples of Other Iterable Objects

Other examples of iterable objects include:

  • Maps: Can be iterated over using for...of to access key-value pairs.
  • Sets: Can be iterated over using for...of to access unique values.
let map = new Map();
map.set('a', 1);
map.set('b', 2);

for (let [key, value] of map) {
  console.log(key, value);  // 'a' 1, 'b' 2
}
Enter fullscreen mode Exit fullscreen mode
let set = new Set([1, 2, 3, 4]);

for (let value of set) {
  console.log(value);  // 1, 2, 3, 4
}
Enter fullscreen mode Exit fullscreen mode

Generators and Iterables

Generators are a special type of function that can be used to create iterable objects. They are defined using the function* syntax and use the yield keyword to produce values.

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

let gen = myGenerator();
for (let value of gen) {
  console.log(value);  // 1, 2, 3
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, iterable objects are a fundamental concept in JavaScript that enables us to work with sequences of values in a flexible and efficient way. By understanding how to create and use iterable objects, we can write more effective and scalable code. Whether you're working with arrays, strings, maps, or sets, iterable objects provide a powerful tool for data processing and manipulation.

Top comments (0)