scrimba
Learning JavaScript
Learning JavaScript: Iterators
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Learning JavaScript: Iterators
AboutCommentsNotes
Learning JavaScript: Iterators
Expand for more info
index.js
run
preview
console
// iterators

// iterators

// any object that implements the Iterator protocol, namely having a next() method that returns an
// object with two properties:
//
// value: the next value in the sequence
// done: if true, the last value in the sequence has been consumed. If value is present, that
// is also the iterator's return value




























function makeIterator(start, end, step) {
let nextIndex = start;
let count = 0;

const rangeIterator = {
next: function() {
let result;
if (nextIndex < end) {
result = { value: nextIndex, done: false };
nextIndex += step;
count += 1;
return result;
}
return { value: count, done: true };

}
};
return rangeIterator;
}

const iterator = makeIterator(1, 10, 2);
let result = iterator.next();
while (!result.done) {
console.log(result.value);
result = iterator.next();
}
Console
/index.html
-6:13