---
tags: evergreen,
aliases: 
  - 
---
# Iterables & Iterators
| Status: #watering | Parent:[[JavaScript]] | plants: | 
| ----------------- | ------- | ------- |
-   Iterables is an object which has a property method, the key for which is `Symbol.iterator`. The method should return an **iterator**. An iterator is an object with a `next` method. An iterator’s `next` method should return an object that has the following properties:
	-   `value`, any type
	-   `done`, a Boolean
```js
const obj = { // <- iterable object
    [Symbol.iterator]() {
        let val = 0;

        return {
            next() { // <- iterator
                return { value: val++, done: val > obj.maxValue };
            }
        };
    },
  
    maxValue: 10
};

for(const value of obj) {
    console.log(value);
}
/* -> 0
   -> 1
   -> ...
   -> 9
*/

console.log(...obj);
// -> 0 1 2 3 4 5 6 7 8 9

// Manual Iteration
const iterator = obj[Symbol.iterator]();

console.log(iterator.next().value); // -> 0
console.log(iterator.next().value); // -> 1
console.log(iterator.next().value); // -> 2
console.log(iterator.next().value); // -> 3
```
* By following the iterable format, we’ve defined how our object behaves inside for-of loops and with the spread operator. This is because for-of loops and the spread operator use iterables under the hood.
* We can do this with built-in iterators as well like arrays, strings, maps, and sets (not objects)
```js
const arr = [1, 2, 3, 4, 5];
const iterator = arr[Symbol.iterator]();

console.log(iterator.next().value); // -> 1
console.log(iterator.next().value); // -> 2
console.log(iterator.next().value); // -> 3

console.log(...iterator) // infinete loop => break
```


