Iterables are data structures that can be looped over (iterated) using the
for...of loop. In JavaScript, several built-in objects are
iterables by default, including Strings, Arrays, Sets, and Maps.
The for...of loop is the standard way to iterate over iterable objects. Its
syntax is clean and it works by getting the values directly.
for (const value of iterable) {
// code block to be executed
}
A JavaScript string is an iterable. You can loop over it to access each character one by one.
const name = "Mim";
for (const x of name) {
console.log(x);
}
// Output: M i m
Arrays are the most common iterables. for...of gives you the values rather
than the indexes (unlike a traditional for loop).
const colors = ["Red", "Blue", "Green"];
for (const color of colors) {
console.log(color);
}
ES6 introduced two new data collections that are also iterables:
// Iterating over a Set
const letters = new Set(["a", "b", "c"]);
for (const x of letters) {
console.log(x);
}
Symbol.iterator method. This method is called by the
for...of loop to set up the iteration sequence.
for...of loop is designed specifically for
iterables{} are not iterable by defaultfor...of iterates over values, not keys or properties