JavaScript Iterables
An iterable is any object that can be looped over using a for..of
loop.
The for..of
loop is a new feature introduced in ES6 (ECMAScript 2015) that allows you to loop over the values of an iterable object. for learn more about for..of loop click here.
Iterable objects in JavaScript include arrays, strings, maps, sets, and some built-in objects such as NodeList and arguments.
An object is considered iterable if it has a special method called Symbol.iterator
.
This method returns an iterator object, which has a next()
method that returns the next value in the iteration sequence.
Here is an example of using a for..of
loop with an array:
const numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
In this example:
- The
for..of
loop iterates over each value in thenumbers
array and logs it to the console.
You can also create your own iterable objects in JavaScript by implementing the Symbol.iterator
method.
As an example:
const myIterable = {
[Symbol.iterator]: function* () {
yield 1;
yield 2;
yield 3;
},
};
for (let value of myIterable) {
console.log(value);
}
In this example:
- We define an iterable object called
myIterable
that returns three values using theyield
keyword. - The
for..of
loop then iterates over each value and logs it to the console.
Summary:
- Iterable objects in JavaScript are objects that can be looped over using a
for..of
loop. - Iterable objects have a special method called
Symbol.iterator
that returns an iterator object, which has anext()
method that returns the next value in the iteration sequence.