Javascript - Iterator

About

In Javascript, an iterator is an iterator

Interface

An object has an iterator when it has:

  • a property named Symbol.iterator that return an object that implement the iterator interface. ie with:
    • a next function that returns an object called the IteratorResult with the following properties:
      • value - the returned value
      • done - a boolean that return true when this is no more element to return ( - if any.
    • [optional] a return function that returns the same IteratorResult than the next function. This function is called when:
      • the iteration reaches the last value,
      • or is stopped by a break

Example

How to create an iterator

var Fib = {
 [Symbol.iterator]() {
     var n1 = 1, n2 = 1;
     return {
         next() {
             var current = n2;
             n2 = n1;
             n1 = n1 + current;
             return { value: current, done: false };
         },
         return(v) {
             console.log('Done');
             return { value: v, done: true };
         }
     };
  }
};
for (var v of Fib) {
    console.log( v );
    if (v > 50) break;
}

How to read an iterator

Example with FormData

  • Buildiing the iterator object
let formData = new FormData();
formData.append('username', 'Nico');
formData.append('age', '10');
  • The For over the object implementing an iterator
console.log("For loop");
for (var entry of formData) {
    console.log( entry );
}
  • The while iteration over the iterator
console.log("While loop");
let it = formData.entries();
let result = it.next();
while (!result.done) {
 console.log(result.value); 
 result = it.next();
}

Documentation / Reference


Powered by ComboStrap