Explain the difference between an iterable and an iterator in JavaScript.
Explain the difference between an iterable and an iterator in JavaScript.
350
01-Nov-2023
Updated on 02-Nov-2023
Aryan Kumar
02-Nov-2023In 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.