ES6 ~ Iterables and Iterators - rohit120582sharma/Documentation GitHub Wiki

Iterables

Iterables are data structures which provide a mechanism to access its elements in a sequential manner. JavaScript provides array, maps, sets and string with an iterable property, plain objects do not have this by default.

An object is considered iterable if it implements the method named Symbol.iterator. The result of obj[Symbol.iterator] is called an iterator. It handles the further iteration process.

The Symbol.iterator method is called automatically by for..of, but we also can do it directly. Loops like for...of have a built-in mechanism to consume iterables until the done value evaluates to true.

Iterator

An iterator moves over the data structure and provides the elements sequentially.

It is an object with a function named next that returns an object which contains a value and a done property.

The value indicates the current data value pointed by the iterator and done is a boolean that tells us if the iterator has reached the last element in the data structure.

let arr = [8000, 8001, 8002];

// Iterate over the object for values automatically
for (let val of arr) {
    console.log(value);
}

// Iterate over the object for values manually
let iterator = arr[Synmbol.iterator]();
console.log(iterator.next()); // { done: false, value: 8000 }
console.log(iterator.next()); // { done: false, value: 8001 }
console.log(iterator.next()); // { done: false, value: 8002 }
console.log(iterator.next()); // { done: true, value: undefined }

⚠️ **GitHub.com Fallback** ⚠️