Iterator In JS

Introduction to Iterator:-

Iterator is an object which allows us to access a collection of objects one at a time.

The following built-in types are by default iterable −

  • String

  • Array

  • Map

  • Set

An object is considered iterable, if the object implements a function whose key is [Symbol.iterator] and returns an iterator. A for…of loop can be used to iterate a collection.

The following list of techniques doesn’t claim to be complete. It’ll show some of the most frequently used approaches.

In order to demonstrate the processing of the single characters of our string, we’ll use the following function:

for  loop

The classic approach — a simple for loop:

const str = ‘banana’;
const process = (character) => {
// …
};
const str = ‘banana’;
// bracket notation
for (let i = 0; i < str.length; i++) {
process(str[i]);
}
// charAt()
for (let i = 0; i < str.length; i++) {
process(str.charAt(i));

}

for…of

This statement was introduced with ECMAScript 2015 and can be used with iterable objects. It’s more convenient to write than a classic for loop if you don’t care about the current index in the loop body.

const str = ‘banana’;
for (let c of str) {
process(c)
}

forEach()

This is the functional version of a for loop. Many people prefer it over for…of and for loops because it’s a higher-order function, and it helps to stick to a programming style that leverages immutability (see the Airbnb style guide in the references).

One downside is you need to convert the string into an array before iterating. If performance really matters in your use case (and it usually doesn’t), it might not be your first choice.

const str = ‘banana’;

[str].forEach(process)

Leave a Reply