JavaScript Interview Question: What are Iterables and Iterators?

Aman
3 min readMar 15, 2022
Photo by Sigmund on Unsplash

An iterable is any data structure that lets us access its elements. Some built in examples are: strings, arrays, maps and sets.

An iterator is an object that has the ability to access items from its collection one at a time and keep track of the current position.

So what exactly is the purpose of iterables and iterators?

In ES6, they were introduced to allow us to access sequences of data in a better way. They did this by giving us access to the data as opposed to figuring out how to access the data. Accessing data prior to ES6 was done via for, while and do while loops.

And now we can iterate over built in data structures using the for of loop. Here is an example with a string, array, map and set.

So what exactly is the iterable protocol to allow this to occur?

The iterable protocol will determine if an object is iterable. And for the object to be iterable, it must have a method at the key [Symbol.iterator].

As shown by our example, string is an iterable and has a method at the key [Symbol.iterator], while an object is not an iterable and does not have a method at the key [Symbol.iterator].

Some of the important characteristics for an iterable protocol: the object needs to have a next() method. This next() method will return two important properties:

  1. value: current element
  2. done: boolean to determine whether there are more items to iterate over.

When the done value is true, we will not longer have any more items to iterate over.

Build composable applications

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →

Learn More

--

--