Since 2015, JavaScript has improved immensely.
It’s much more pleasant to use it now than ever.
In this article, we’ll look at JavaScript iterable objects.
Iterable Data Sources
We can use the for-of loop to iterate through various kinds of iterable objects.
For example, we can loop through an array by writing:
const arr = ['foo', 'bar', 'baz'\];
for (const x of arr) {
console.log(x);
}
Then we get:
foo
bar
baz
logged.
We can also use it with strings.
For example, we can write:
const arr = \['foo', 'bar', 'baz'\];
for (const x of 'foo') {
console.log(x);
}
Then we get the letters of 'foo'
logged individually.
Maps are also itrerable objects, so we can use it with the for-of loop.
For instance, we can write:
const map = new Map().set('foo', 1).set('bar', 2);
for (const \[key, value\] of map) {
console.log(key, value);
}
We created a map with some keys and values with the Map
constructor.
Then in the for-of loop, we looped through each entry and destructured the key and value from the map entries.
So we get:
foo 1
bar 2
from the console log.
Sets are also iterables that can be iterated through.
For example, we can write:
const set = new Set().add('foo').add('bar');
for (const x of set) {
console.log(x);
}
We created a set and added some items to it.
Then we used the for-of loop with it.
And so we get:
foo
bar
from the console log.
arguments
is an object that’s available inside traditional functions to get the arguments from a function call.
We can use it with the for-of loop as it’s an iterable object:
function logArgs() {
for (const x of arguments) {
console.log(x);
}
}
logArgs('foo', 'bar');
We passed in 'foo'
and 'bar'
to the logArgs
function and we get the values from the for-of loop.
DOM NodeLists can also be iterated through with the for-of loop.
For instance, we can write:
for (const div of document.querySelectorAll('div')) {
console.log(div);
}
to loop through all the divs on the page.
Iterable Computed Data
If a function returns an iterable object, we can loop through it with the for-of loop.
For instance, we can write:
const arr = \['a', 'b', 'c'\];
for (const \[index, element\] of arr.entries()) {
console.log(index, element);
}
Then we get:
0 "a"
1 "b"
2 "c"
We get the indexes and the elements with the arr.entries
method and we get the values each entry inside the loop body.
Plain Objects are not Iterable
Plain objects aren’t iterable, so we can’t use them with the for-of loop.
For instance, something like:
for (const x of {}) {
console.log(x);
}
would give us the ‘Uncaught TypeError: {} is not iterable’ error.
Objects aren’t iterable because either we loop through the properties of an object to examine its structure.
Or we loop through the data.
This should be kept separate to avoid confusing objects with other kinds of data structures.
If we want to make an object iterable, we can create the Symbol.iterator
generator method to make it so.
Conclusion
The for-of loop can iterate through many kinds of iterable objects.