Advertisement
Synchronous iteration was introduced in ES6 and it works with below set of components,
Iterable: It is an object which can be iterated over via a method whose key is Symbol.iterator.
Iterator: It is an object returned by invoking [Symbol.iterator]() on an iterable. This iterator object wraps each iterated element in an object and returns it via next() method one by one.
IteratorResult: It is an object returned by next() method. The object contains two properties; the value property contains an iterated element and the done property determines whether the element is the last element or not.
Let's demonstrate synchronous iteration with an array as below
1const iterable = ["one", "two", "three"];
2
3const iterator = iterable[Symbol.iterator]();
4
5console.log(iterator.next()); // { value: 'one', done: false }
6
7console.log(iterator.next()); // { value: 'two', done: false }
8
9console.log(iterator.next()); // { value: 'three', done: false }
10
11console.log(iterator.next()); // { value: 'undefined, done: true }Advertisement
JavaScript Coding Exercise 65
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement