In JavaScript, iterable and iterator are related concepts, but they serve different purposes and have distinct characteristics:
Iterable:
An iterable is an object that defines how it can be iterated over. It is any object that has a special method called
Symbol.iterator that returns an iterator.
Iterables can be looped over using the for...of loop, which simplifies the process of accessing their elements.
Examples of iterables include arrays, strings, sets, maps, and user-defined iterable objects.
Iterator:
An iterator is an object responsible for keeping track of the current position during iteration and providing the next value in a sequence.
It has two important methods: next() and return(). The
next() method is used to retrieve the next value in the sequence and also returns information about whether the iteration is complete. The
return() method is used to signal the end of iteration and can be used to clean up resources if necessary.
Iterators are obtained from an iterable by calling the Symbol.iterator method on the iterable object. This returns an iterator object.
Iterators maintain internal state, such as the current position, which allows them to produce the next value when
next() is called. If the iteration is complete, the iterator returns an object with the
done property set to true.
Here's a simple example to illustrate the difference:
const iterable = [1,
In this example, iterable is an array, and we obtain an iterator from it using the
Symbol.iterator method. The iterator object keeps track of the current position and provides the values as we call its
next() method.
To summarize, an iterable is an object that can be iterated over, while an iterator is the object that facilitates the iteration, maintaining its state and providing the values. Iterable objects provide iterators to allow efficient and controlled access to their elements.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In JavaScript, iterable and iterator are related concepts, but they serve different purposes and have distinct characteristics:
Iterable:
Iterator:
Here's a simple example to illustrate the difference:
In this example, iterable is an array, and we obtain an iterator from it using the Symbol.iterator method. The iterator object keeps track of the current position and provides the values as we call its next() method.
To summarize, an iterable is an object that can be iterated over, while an iterator is the object that facilitates the iteration, maintaining its state and providing the values. Iterable objects provide iterators to allow efficient and controlled access to their elements.