This content originally appeared on Bits and Pieces - Medium and was authored by Aman
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:
- value: current element
- 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 web 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
- How We Build Micro Frontends
- How we Build a Component Design System
- The Composable Enterprise: A Guide
- 7 Tools for Faster Frontend Development in 2022
JavaScript Interview Question: What are Iterables and Iterators? was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Aman
Aman | Sciencx (2022-03-16T13:43:25+00:00) JavaScript Interview Question: What are Iterables and Iterators?. Retrieved from https://www.scien.cx/2022/03/16/javascript-interview-question-what-are-iterables-and-iterators/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.