JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What are iterators in JavaScript?

Asked on Jul 26, 2024

Answer

Iterators in JavaScript are objects that allow you to traverse through a collection, such as an array or a string, one element at a time. They provide a standardized way to access elements sequentially without exposing the underlying structure.
// Example of using an iterator with an array
        const array = ['a', 'b', 'c'];
        const iterator = array[Symbol.iterator]();

        console.log(iterator.next()); // { value: 'a', done: false }
        console.log(iterator.next()); // { value: 'b', done: false }
        console.log(iterator.next()); // { value: 'c', done: false }
        console.log(iterator.next()); // { value: undefined, done: true }
Additional Comment:
  • An iterator object implements the "next" method, which returns an object with two properties: "value" (the current element) and "done" (a boolean indicating if the iteration is complete).
  • The "Symbol.iterator" is a built-in symbol that specifies the default iterator for an object.
  • Iterators are commonly used in loops, such as "for...of", to iterate over iterable objects.
✅ Answered with JavaScript best practices.
← Back to All Questions