How to Convert an Array to an Iterator in JavaScript

To convert an array to an iterator in JavaScript, you can use the “Symbol.iterator” property. Arrays implement the iterable protocol, meaning they have a built-in Symbol.iterator property that returns an iterator object.


const mainArray = [11, 21, 19, 46, 18];
const iterator = mainArray[Symbol.iterator]();



{ value: 11, done: false }
{ value: 21, done: false }
{ value: 19, done: false }
{ value: 46, done: false }
{ value: 18, done: false }

In this code, we have an array called mainArray.

We used the “Symbol.iterator” property of the array to create an iterator called an iterator.

In the next step, we called the “next()” method of the iterator to get the next value in the array.

The “next()” method returns an object with two properties: value, the current value in the array, and, done, a boolean value suggesting whether the iteration is complete.

The output of the “console.log()” statements demonstrates the iteration process.

Leave a Comment