Snippet - Array Iterators

5 years ago

Here are a few examples of how to create iterators and how to consume them using a simple Array. As of today, Array.values() is only available in Firefox Nightly and Safari, so you will need Babel to transpile or a polyfill like shown below.

Array.values Polyfill

Array.prototype.values =
  Array.prototype.values ||
  function() {
    return this[Symbol.iterator]()
  }

Code

const array = [1, 2, 3, 4]

const arrayIteratorWithSymbol = array[Symbol.iterator]()
const arrayIteratorWithValues = array.values()

console.log('Array Iterator With Symbol.iterator')
for (let x of arrayIteratorWithSymbol) {
  console.log(x)
}

console.log('Array Iterator With values')
for (let x of arrayIteratorWithValues) {
  console.log(x)
}

Results

Array Iterator With Symbol.iterator
1, 2, 3, 4

Array Iterator With values
1, 2, 3, 4

Alternative Ways to Consume - next() and Spread Operator

console.log('Using next()')
const arrayIteratorWithNext = array.values()
for (let x = 0; x < array.length; x++) {
  console.log(arrayIteratorWithNext.next())
}

console.log('Using Spread operator')
const arrayWithSpread = array.values()
const [...spreadTest] = arrayWithSpread
spreadTest.forEach(x => console.log(x))

Results

Using next()
1, 2, 3, 4

Using Spread operator
{
  "value": 1,
  "done": false
}
{
  "value": 2,
  "done": false
}
{
  "value": 3,
  "done": false
}
{
  "value": 4,
  "done": false
}

Source Code
Discuss on Twitter