A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-iterator/ below:

JavaScript Iterator - GeeksforGeeks

JavaScript Iterator

Last Updated : 10 Aug, 2025

A JavaScript Iterator is an object that lets you traverse through a list or collection one item at a time. It follows the iterator protocol, meaning it must have a next() method that returns an object in the form:

Using for.of loop, we can iterate over any entity (for eg: an object) which follows iterable protocol. The for.of loop is going to pull out the value that gets a return by calling the next() method each time.

Example: This example uses a for..of loop to iterate over the array.

javascript
const array = ['a', 'b', 'c'];
const it = array[Symbol.iterator]()
for (let value of it) {
    console.log(value)
}
Create our own iterable object:

Iterable protocol: The object must define a method with 'Symbol.iterator' the key which returns an object that itself follows iterator protocol. The object must define the 'next' method which returns an object having two properties 'value' and 'done'

Syntax:

{value: 'item value', done: boolean}

Error scenario:

var newIt = arr[Symbol.iterator]

newIt()

//Because it does not properly bind


Uncaught TypeError: Cannot convert undefined or null to object
//How we can fix this
//var newIt = arr[Symbol.iterator].bind(arr);

newIt()


Array Iterator { }
JS
{ value: <currentItem>, done: <boolean> }

An object is iterable if it has a [Symbol.iterator] method that returns an iterator. You can check this with:

JS
typeof obj?.[Symbol.iterator] === "function"

For example, Array.prototype contains a [Symbol.iterator] method (specifically values()), so arrays are iterable by default. Other built-in iterables include String, Map, and Set—their prototypes also define [Symbol.iterator].

javascript
let obj = {
  data: [1, 2, 3],
  [Symbol.iterator]() {
    let i = 0;
    return {
      next: () => ({
        value: this.data[i],
        done: i++ >= this.data.length
      })
    };
  }
};

for (let x of obj) 
  console.log(x);


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4