What is an iterable in JavaScript?
What is an iterable in JavaScript?
341
01-Nov-2023
Updated on 02-Nov-2023
Aryan Kumar
02-Nov-2023In JavaScript, an iterable is an object that defines how it can be iterated over. Iterables are a fundamental concept in modern JavaScript and are used for looping over the elements or values contained within the object. To be considered an iterable, an object must implement the iterator protocol.
The iterator protocol involves having a special method, Symbol.iterator, which returns an iterator object. This iterator object, in turn, should have a next() method that is used to retrieve the next value in the sequence.
Here's what defines an iterable in JavaScript:
Symbol.iterator Method: An iterable object must have a Symbol.iterator method. When called, this method returns an iterator object.
Iterator Object: The iterator object returned by Symbol.iterator should have a next() method. The next() method is used to retrieve the next value in the iteration.
next() Method: The next() method returns an object with two properties:
Examples of built-in iterables in JavaScript include arrays, strings, maps, and sets. Here's how you can identify and use an iterable:
In these examples, array, string, and map are all iterable objects. You can use a for...of loop to easily iterate over their elements or key-value pairs. These objects adhere to the iterator protocol, which makes them iterable.