Contents

About iterator

   Aug 4, 2023     2 min read

This post is about Iterators.

When I was testing my code, I came across a solution in someone else’s code that utilized an iterator object. I had a general idea of the concept, but I had never seen it utilized before, so I thought it would be interesting to learn more about it and write a tutorial.

What is an Iterator Object?

An Iterator object is an object that provides an interface used in JavaScript to iterate over iterable objects. An iterator is used to access and iterate over each element within a traversable object.

An iterator has two functions.

next() function

This method is called each time the iterator object is traversed. Each time it is called, it returns an iterator result object that points to the next element within the traversable object. The return object has two properties: value and done. value: The value of the element the iterator is currently pointing to. done: true when all traversable objects have been traversed, false otherwise.

Symbol.iterator function

This method is a special symbolic identifier (Symbol) that returns an iterator object. It is used to traverse through the iterable objects.

Example
const arr = [1, 2, 3];
const iterator = arr[Symbol.iterator](); // get the iterator of the array

console.log(iterator.next()); // output: { value: 1, done: false }
console.log(iterator.next()); // output: { value: 2, done: false }
console.log(iterator.next()); // output: { value: 3, done: false }
console.log(iterator.next()); // Output: { value: undefined, done: true }

const iterator = arr[Symbol.iterator](); // Initialize an iterator in an array

-----

// Convert a string to an array
const str = 'Hello';
const arr = Array.from(str);
console.log(arr); // Output: ['H', 'e', 'l', 'l', 'o']

-----

// Create an array by applying a mapping function to an iterable object
const set = new Set([1, 2, 3]);
const arr = Array.from(set, (item) => item * 2);
console.log(arr); // Output: [2, 4, 6]

-----

// Create an array of numbers from 1 to N
const newArray = Array.from({ length: 9 }, (value, index) => index + 1);
console.log(newArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

See

Array is an iterable object, so you can use an iterator to traverse the elements of an array. String, Set, Map, etc. are also iterable objects and can be traversed using an iterator.