Next: , Previous: , Up: ES2015   [Index]


4.8 Iterators—For–Of

Iterator objects enable custom iteration. Generalize for..in to custom iterator-based iteration with for..of.

let fibonacci = {
  [Symbol.iterator]() {
    let pre = 0, cur = 1;
    return {
      next() {
        [pre, cur] = [cur, pre + cur];
        return { done: false, value: cur }
      }
    }
  }
}

for (var n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000)
    break;
  console.log(n);
}