JavaScript Iterators allow to process of every element of a container while isolating the user from the internal structure of the container. An iterator is an object that is returned by the Symbol.iterator()
method.
The iterator protocol provides the next()
method to access each element of the iterable (data structure) one at a time.
JavaScript iterators were introduced in ES6 and they are used to loop over a sequence of values, usually some sort of collection.
value
: The next value in the iteration sequence.done
: This is true if the last value in the sequence has already been consumed. If the value is present alongside, it is the iterator’s return value.
Must Read: JavaScript iterable
JavaScript Iterators
Simple example code allows creation of a simple range iterator which defines a sequence of integers from start
(inclusive) to end
(exclusive) spaced step
apart. Its final return value is the size of the sequence it created, tracked by the variable iterationCount
.
<!DOCTYPE html>
<html>
<body>
<script>
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
let nextIndex = start;
let iterationCount = 0;
const rangeIterator = {
next() {
let result;
if (nextIndex < end) {
result = { value: nextIndex, done: false }
nextIndex += step;
iterationCount++;
return result;
}
return { value: iterationCount, done: true }
}
};
return rangeIterator;
}
const it = makeRangeIterator(1, 10, 2);
let result = it.next();
while (!result.done) {
console.log(result.value);
result = it.next();
}
console.log("Iterated over sequence of size: ", result.value);
</script>
</body>
</html>
Output:
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
Let’s look at an example of iterables having Symbol.Iterator()
<script>
const arr = [1, 2 ,3];
const arrIterator = arr[Symbol.iterator]();
console.log(arrIterator);
const str = 'hello';
const strIterator = str[Symbol.iterator]();
console.log(strIterator);
</script>
Output:
Array Iterator {}
StringIterator {}
Do comment if you have any doubts or suggestions on this Js tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version