Exercise on Iterators and Generators
Explore practical exercises focused on JavaScript iterators and generators. Learn to create and manipulate iterable objects, handle generator functions, and master iteration logic including infinite sequences and lazy filtering. This lesson enhances your ability to work with dynamic data and understand core ES6 features.
We'll cover the following...
These exercises help you explore how iterators and generators work. You will get a chance to play around with iterators and generators, which will result in a higher depth of learning experience for you than reading about the edge cases.
You can also find out if you already know enough to command these edge cases without learning more about iterators and generators.
Exercise 1:
What happens if we use a string iterator instead of an iterable object in a for-of loop?
let message = 'ok';
let messageIterator = message[Symbol.iterator]();
messageIterator.next();
for ( let item of messageIterator ) {
console.log( item );
}
Solution
Similarly to generators, in case of strings, arrays, DOM elements, sets, and maps, an iterator object is also an ...