Iterator and Iterable

 Iterator and Iterable


The iterator and iterable protocols provide a way to define and iterate over collections or sequences of data in JavaScript.



const myIterable = {

  [Symbol.iterator]() {

    let count = 0;

    return {

      next() {

        count++;

        if (count <= 5) {

          return { value: count, done: false };

        }

        return { done: true };

      }

    };

  }

};


for (const value of myIterable) {

  console.log(value);

}

// Output: 1, 2, 3, 4, 5

In the example above, the myIterable object implements the iterable protocol by defining a method with the key [Symbol.iterator]. The method returns an iterator object with the next method, which provides the next value in the sequence.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...