# Iterators in JavaScript

In this blog post, we will see what are Iterators and how we use them.

### What is an Iterator?

An iterator is an object which confirms to *iterator protocol,* which is a set of conventions to be followed by the object, for a sequence of iterable such arrays, strings, maps, sets, etc. The protocol states that the object must implement a `next` method that returns an object with two properties:

1. **done:** boolean value indicating if the iteration is finished or not.
    
2. **value:** the current value of the iteration. it can be omitted when done is true.
    

There are two optional methods that an iterator can implement, namely `return` and `throw`, both of which accept 0 or 1 arguments. The `return` method informs the iterator that there will be no more `next` calls and it can perform any cleanup if needed. The `throw` method informs the iterator that the caller detected an error condition and an error instance can be passed.

Iterating through the values of the iterator consumes them, so any calls to the iterator after the last element in the sequence is consumed would return the `{done: true}`.

While we can imagine a sequence as being represented by an array of items, and so an iterator for a sequence to be an array, while this is true, not all iterators are arrays. In other words, the space for the arrays needs to be allocated completely, i.e., we need to think about how many items are there in this array. However, as mentioned above, iterators are consumed only as necessary and thus can express sequences of unlimited size.

### Example

Let us create a simple iterator that generates the sequence of natural numbers from `0` to `Infinity`, where we can decide on which number we want to stop. We could also loop through the iterator using a `while` loop until it is done.

```javascript
function naturalNumbers() {
    let n = 0;
    return {
        next: function() {
            n++;
            return { value: n, done: false };
        }
    };
}

// Create an iterator
const numbers = naturalNumbers();

// Call the next() method
console.log(numbers.next()); // { value: 1, done: false }
console.log(numbers.next()); // { value: 2, done: false }
console.log(numbers.next()); // { value: 3, done: false }
// ...

let result = numbers.next();
while (!result.done) {
    console.log(result.value);
    result = numbers.next();
}
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">JavaScript provides a <code>for...of</code> loop which makes it easier to work with iterators on iterables, which are iterators with a<code>[Symbol.iterator]()</code> method that returns itself.</div>
</div>

### How to create custom iterators?

Sometimes, we may want to create our own custom iterators that implement some specific logic or algorithm. For example, suppose we want to create an iterator that generates the Fibonacci sequence:

```javascript
function fibonacci() {
    let a = 0;
    let b = 1;
    return {
        next: function() {
                let c = a + b;
                a = b;
                b = c;
                return { value: c, done: false };
        },
        [Symbol.iterator]: function() {
            return this;
        }
    };
}

// Create an iterator
const fibo = fibonacci();

// Use the for...of loop
for (const n of fibo) {
    console.log(n);
    if (n > 1000) break; // stop the loop after reaching 1000
}
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If you look closely, iterators use the concept of closures while following the iterator protocol.</div>
</div>

### Conclusion

In this blog post, we learned about iterators in JavaScript, which are objects that allow us to iterate over iterable data structures. We also learned how to iterate over iterators and how to create custom iterators.

Iterators are powerful features of JavaScript that enable us to write expressive and concise code for working with sequences of values.

I hope this blog post was informative and helpful for you. Consider hitting the like button and feel free to add any comments or questions.

Thank you for reading and happy coding!
