Iterators!!!

const formSteps = [
    "CONTACT", 
    "EXPERIENCE", 
    "EDUCATION"
];

What is an Iterator?

  • In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. (From MDN Web Docs)
  • An iterator is mechanism that allows you to get each item in a collection in order.
const myCollection = [1, 2, 3, 4, 5];
const y = myCollection.forEach(n => n * 2);
// => [2, 4, 6, 8, 10]
// => undefined
const x = myCollection.map(n => n * 2);

How do Iterators work?


function createFunction(value) {
    return function() {
        return value;
    }
}

const x = createFunction("some value");

const y = x();
// ƒ () {
//         return value;
//     }
// "some value"

function createIterator(collection) {
    let index = 0;
    
    return function() {
        const result = collection[index];
        index += 1;
        return result;
    }
}

const getNext = createIterator([1, 2, 3, 4, 5])

const value = getNext()

Closure

Iterator Protocol

const iterator = createIterator([1, 2, 3, 4, 5]);

let result = iterator.next(); 
// { value: 1, done: false }

while (!result.done) {
 console.log(result.value);
 result = it.next();
}

Iterators

By Becca Nelson