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:

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

 

Class based solution

Edit

 

See also

Edit
  1. JavaScript - ECMAScript / ES versions and features

References

Edit
  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
1
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