JS Coding Questions Logo
JS Coding Questions
#236💼 Interview💻 Code

How does synchronous iteration works

Advertisement

728x90

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

javascript
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

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 65

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
236of476