In the world of programming, JavaScript is recognized as a universal language, and one of the interesting and practical concepts in this language is Iterables. Iterables are a concept in JavaScript that allows us to utilize a collection of data in an order that can be sequentially traversed. In simple terms, Iterables are pieces of data that we can loop over or iterate through.
To better understand, imagine Iterables as books that we can read page by page. If this book includes a list of names of a favorite music band, we can use a for...of loop to easily iterate through the members of this band.
In fact, in JavaScript, structures like Array, Map, and Set are inherently iterable. However, you can also make a custom structure iterable by defining a special [Symbol.iterator]. Using the [Symbol.iterator] feature enables a structure to be treated as an iterable. It acts as a key to specify how it should be iterated.
For example, you can define a simple Iterable with a [Symbol.iterator] feature that produces a random value each time. In this way, you can create a valid iterable structure to be able to use it wherever necessary.
Let's take a look at a code snippet that explains more about this topic:
const randomNumbers = {
[Symbol.iterator]() {
return {
next() {
return { value: Math.random(), done: false };
}
};
}
};
for (let number of randomNumbers) {
console.log(number);
if (number > 0.9) break; // end the loop when the value is greater than 0.9
}
This piece of code generates interesting values. Let's analyze it together:
const randomNumbers = {
this line defines a structure named
randomNumbers
.[Symbol.iterator]() {
this feature allows
randomNumbers
to act as an iterable.return {
it returns an object that contains a method
next()
.next() {
this method specifies how the iteration works.
return { value: Math.random(), done: false };
this line returns a random value and indicates that the iteration has not finished.
for (let number of randomNumbers) {
starts a loop for iterating over the values of
randomNumbers
.console.log(number);
prints the random value at each iteration.
if (number > 0.9) break;
breaks the loop if the value is greater than
0.9
.