JavaScript Iterables are objects that implement the iterable protocol, which allows them to be iterated over using the for...of
loop. The iterable protocol requires an object to have a method called Symbol.iterator
, which returns an iterator object.
Iterators are objects that implement the iterator protocol, which requires them to have a method called next()
. The next()
method returns an object with two properties: value
and done
. The value
property is the next value in the iteration, and the done
property is a boolean that indicates whether the iteration is complete.
JavaScript provides several built-in iterables, including arrays, strings, maps, and sets. It is also possible to create custom iterables by implementing the iterable protocol.
Here are some examples of using the for...of
loop with different types of iterables:
const arr = [1, 2, 3];
for (const num of arr) {
console.log(num);
}
This will output:
1
2
3
const str = 'hello';
for (const char of str) {
console.log(char);
}
This will output:
h
e
l
l
o
const map = new Map([
['a', 1],
['b', 2],
['c', 3]
]);
for (const [key, value] of map) {
console.log(key, value);
}
This will output:
a 1
b 2
c 3
const set = new Set([1, 2, 3]);
for (const num of set) {
console.log(num);
}
This will output:
1
2
3
Here is an example of creating a custom iterable:
const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
};
for (const num of myIterable) {
console.log(num);
}
This will output:
1
2
3
In this example, we define an object with a method called Symbol.iterator
that returns a generator function. The generator function uses the yield
keyword to return each value in the iteration.
JavaScript Iterables are a powerful feature that allow for easy iteration over a wide range of data types. By implementing the iterable protocol, it is possible to create custom iterables that can be used with the for...of
loop.