JavaScript Iterables

Objects that can be iterated over with for..of are called iterable.

Technically, iterables must implement the Symbol.iterator method.

Iterating Over a String

You can use a for..of loop to iterate over the elements of a string:

Example

for (const x of "W3Schools") {
  // code block to be executed
}

Iterating Over an Array

You can use a for..of loop to iterate over the elements of an Array:

Example

for (const x of [1,2,3,4,5] {
  // code block to be executed
}

JavaScript Iterators

The iterator protocol defines how to produce a sequence of values from an object.

An object becomes an iterator when it implements a next() method.

The next() method must return an object with two properties:

  • value (the next value)
  • done (true or false)