Iterating over a collection of data is an important part of programming. Prior to ES2015, JavaScript provided statements such as for
, for...in
, and while
, and methods such as map()
, filter()
, and forEach()
for this purpose. To enable programmers to process the elements in a collection one at a time, ES2015 introduced the iterator interface.
An object is iterable if it has a Symbol.iterator
property. In ES2015, strings and collections objects such as Set
, Map
, and Array
come with a Symbol.iterator
property and thus are iterable. The following code gives an example of how to access the elements of an iterable one at a time:
const arr = [10, 20, 30];
const iterator = arr[Symbol.iterator]();