Basically an iterator has a function – next() – which allows you to output values step by step.
How it works
Table Of Contents
Code
let array = [1, 2, 3]; let iterator = array[Symbol.iterator]();
console.log(iterator.next()); // prints {done: false, value: 1}
1
2
2
Calling next prints the current state (done => false or true, depending on the amount of values left) and the current value. The cool thing about iterators is, that you can implement them in your own objects.
let iterableObj = {
[Symbol.iterator]() {
let nextVal = 5;
return {
next() {
return {
value: nextVal++,
done: false
}
}
}
}
};
let iterator = iterableObj[Symbol.iterator]();
console.log(iterator.next()); // {done: false, value: 5}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
::Warning Since done is never set to true the code above will run forever. ::