DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on

3 2

Iterators

In ES6 objects are said to be iterable when they implement the iterable interface. Many built-in objects such as arrays, sets and maps implement this interface. User defined objects and classes can also implement the interface.

Iterable objects can also be iterated using the new for of loop, and used with the ... spread operator.

Iterable Interface

An object is said to conform to the iterable interface when the value of its property identified with the shared @@iterator Symbol is a function which returns an iterator.

var iterator = [1,2,3][Symbol.iterator]();

An iterator is any object that implements a next function.

var iterator = [1,2,3][Symbol.iterator]();

console.log(iterator.next); // '[Function]'

The next function can be called repeatedly to step through the iteration. Each time it returns an object that contains two keys, value and done. The values of these keys indicate the current value of the iteration and its completion status respectively.

var iterator = [1,2,3][Symbol.iterator]();

console.log(iterator.next()); // {value:1, done:false}
console.log(iterator.next()); // {value:2, done:false}
console.log(iterator.next()); // {value:3, done:false}
console.log(iterator.next()); // {value:undefined, done:true}

Custom objects and classes can be made iterable by implementing the iterator interface manually.

var iterable = {
  [Symbol.iterator] () {
    return {
      next () {
        // Implement iterator
      }
    }
  }
}

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

If you found this article helpful, please give a ❤️ or share a friendly comment!

Got it