We are going to analyze Iterators in this article. Iterators are a new way to loop over any collection in JavaScript. They were introduced in ES6 and have become really popular since they are widely useful and are used in various places.

We are going to conceptually understand what iterators are and where to use them with examples. We’ll also see some of its implementations in JavaScript.

Introduction

Imagine that you have this array —

const myFavouriteAuthors = [
  'Neal Stephenson',
  'Arthur Clarke',
  'Isaac Asimov', 
  'Robert Heinlein'
];

At some point, you will want to get back all the individual values in the array for printing them on the screen, manipulating them, or for performing some action on them. If I ask you how would you do that? You’ll say — it’s easy. I’ll just loop over them using _for_, _while_, _for-of_ or one of these _looping methods._Example implementations would be —

Image for post

Various looping techniques on arrays

Now, imagine that instead of the previous array, you had a custom data structure to hold all your authors. Like this —

Image for post

Custom Data Structure

Now, myFavouriteAuthors is an object which contains another object allAuthors. allAuthors contains three arrays with keys fiction, scienceFiction, and fantasy. Now, if I ask you to loop over**myFavouriteAuthors** **to get all the authors, what would your approach be?**You can go ahead and try some combination of loops to get all the data.

However, if you did this —

for (let author of myFavouriteAuthors) { 
  console.log(author)
}// TypeError: {} is not iterable

You would get a TypeError saying that the object is not iterable. Let’s see what iterables are and how we can make an object iterable. At the end of this article, you’ll know how to use for-of loop on custom objects, and in this case, on myFavouriteAuthors.

#javascript #es6 #programming #developer #web-development

A Guide to ES6 Iterators in JavaScript with Examples
2.05 GEEK