How to use Symbol iterator Property In Javascript

To make an iterator for an array.

const it = array[Symbol.iterator](); 

So, first, we make an iterator for the “array” named “it”. After creating the iterator we iterate to each value stored in that iterator and push it into another array named “p” with the use of the following code

p.push(word) 

where the word is the value corresponding to the array of elements stored in the iterator. After iterating through each of the elements we get our final array where all the values of the iterator get stored in p.

Example: In this example, we will convert a JavaScript iterator to a JavaScript Array.

javascript
const array = ['Geeks', 'for', 'Geeks'];
let p = []
const it = array[Symbol.iterator]();
console.log(it);

for (let word of it) {
    p.push(word)
}
console.log("After the conversion the array becomes");
console.log(p);

Output
Object [Array Iterator] {}
After the conversion the array becomes
[ 'Geeks', 'for', 'Geeks' ]

How to transform a JavaScript iterator into an array ?

The task is to convert an iterator into an array, this can be performed by iterating each value of the iterator and storing the value in another array.

These are the following ways we can add an iterator to an array:

Table of Content

  • Using Symbol iterator Property
  • Using Array.from Method
  • Using the Spread Operator
  • Using a for…of Loop

Similar Reads

Using Symbol iterator Property

To make an iterator for an array....

Using Array.from Method

We can transform the javascript iterator into a JavaScript array by using the array.from() method....

Using the Spread Operator

We can transform the javascript iterator into a JavaScript array by using the spread operator method...

Using a for…of Loop

To transform a JavaScript iterator into an array using a for…of loop, initialize an empty array, then iterate over the iterator with the loop, pushing each value into the array. This method is straightforward and compatible with all iterable objects....

Contact Us