Languages
[Edit]
EN

JavaScript - create custom iterator for any Object

9 points
Created by:
lena
714

In this short article we would like to show how to create custom iterator for any Object in JavaScript.

Motivation to create own one iterator may be:

  • custom behaving of iterator on existing iterable objects, e.g. Array, etc.
  • support for for..of loops on non-iterable objects.

In the below we create default iterator equivalent that may be base for the target version.

 

Practical example:

// ONLINE-RUNNER:browser;

function ArrayIterator(array) {
    let index = 0;
    this.next = function() {
        if (index < array.length) {
            const result = {
                done: false,
                value: array[index]
            };
            index += 1;
            return result;
        } else {
            return {
                done: true
            };
        }
    };
    this[Symbol.iterator] = function() {
        return this;
    };
}


// Usage example:

const array = [1, 2, 3];
const iterator = new ArrayIterator(array);

for (const item of iterator) {
    console.log(item);
}

Note: Symbol function and for..of loop syntax were introduced in ES6 (ES2015).

 

Class based solution

// ONLINE-RUNNER:browser;

class ArrayIterator {
    #index;
    #array;
    constructor(array) {
    	this.#index = 0;
    	this.#array = array;
    }
    next() {
        if (this.#index < this.#array.length) {
            const result = {
                done: false,
                value: this.#array[this.#index]
            };
            this.#index += 1;
            return result;
        } else {
            return {
                done: true
            };
        }
    };
    [Symbol.iterator]() {
        return this;
    };
}


// Usage example:

const array = [1, 2, 3];
const iterator = new ArrayIterator(array);

for (const item of iterator) {
    console.log(item);
}

 

See also

  1. JavaScript - ECMAScript / ES versions and features

References

  1. Iteration protocols - MDN Docs

Alternative titles

  1. JavaScript - create own iterator for any Object
  2. JavaScript - create custom iterator of any Object
  3. JavaScript - create own iterator of any Object
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join