FrontendDeveloper.in

ECMAScript question detail

Iterators & For..of

String, Array, TypedArray, Map, and Set are all built-in iterables but objects are not iterables by default. Iterators are a new way to loop over any collection in JavaScript. These are objects which defines a sequence and potentially a return value upon its termination. An iterator implements the Iterator protocol by having a next() method that returns an object with two properties:

  1. value: The next value in the iteration sequence.
  2. done: returns true if the last value in the sequence has already been consumed.

You can make the object iterable by defining a Symbol.iterator property on it.

const collection = {
one: 1,
two: 2,
three: 3,
[Symbol.iterator]() {
const values = Object.keys(this);
let i = 0;
return {
next: () => {
return {
value: this[values[i++]],
done: i > values.length
}
}
};
}
};

const iterator = collection[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}

for (const value of collection) {
console.log(value);
}

The for...of statement creates a loop iterating over user defined collection object. But this loop can be used for built-in objects too.

Note: The abrupt iteration termination can be caused by break, throw or return.

Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399