JS Interview #10 — Iterators and Iterables
In this article, we are going to discuss Iterators and Iterables in JavaScript with the help of examples.
JavaScript provides a protocol to iterate over data structures.
The concept of the protocol can be split into:
- iterable
- iterator
JavaScript Iterables & Iterators
The data structures that have the Symbol.iterator()
method is called iterable.
An iterator is an object that is returned by the Symbol.iterator()
method.
The iterator object has a next()
method that returns the next item in the sequence.
const arr = [1, 2 ,3];
const arrIterator = arr[Symbol.iterator]();
console.log(arrIterator);
// output
Object [Array Iterator] {}
const str = 'hello';
const strIterator = str[Symbol.iterator]();
console.log(strIterator);
// output
Object [String Iterator] {}
Iterables Example
const number = [1, 2, 3];
for (let n of number[Symbol.iterator]()) {
console.log(n);
}
// OUTPUT
1
2
3
const str = 'hello';
for (let n of str[Symbol.iterator]()) {
console.log(n);
}
// OUTPUT
h
e
l
l
o
Iterators Example
The iterator object has a next()
method that returns the next item in the sequence.
const arr = ['h', 'e', 'l', 'l', 'o'];
let arrIterator = arr[Symbol.iterator]();
console.log(arrIterator.next()); // {value: "h", done: false}
console.log(arrIterator.next()); // {value: "e", done: false}
console.log(arrIterator.next()); // {value: "l", done: false}
console.log(arrIterator.next()); // {value: "l", done: false}
console.log(arrIterator.next()); // {value: "o", done: false}
console.log(arrIterator.next()); // {value: undefined, done: true}j
Custom Defined Iterator
function displayElements(arr) {
let n = 0;
return {
next() {
if(n < arr.length) {
return {
value: arr[n++],
done: false
}
}
return {
value: undefined,
done: true
}
}
}
}
const arr = ['h', 'e', 'l', 'l', 'o'];
const arrIterator = displayElements(arr);
console.log(arrIterator.next()); // { value: 'h', done: false }
console.log(arrIterator.next()); // { value: 'e', done: false }
console.log(arrIterator.next()); // { value: 'l', done: false }
console.log(arrIterator.next()); // { value: 'l', done: false }
console.log(arrIterator.next()); // { value: 'o', done: false }
console.log(arrIterator.next()); // { value: undefined, done: true }
Key Points to remember
- Iterable added in ES6
- Iterable must implement the method named
Symbol.iterator
- The result of
obj[Symbol.iterator]()
is called an iterator. It handles further iteration processes. - The
Symbol.iterator
method is called automatically byfor..of
, but we also can do it directly. - All collections (Array, Map, Set, WeakMap, WeakSet) all are built-in Iterables.
To understand in a much better way here is the video link