An iterable object in JavaScript is an object that can be iterated over using the iterable protocol. You can iterate over it using a for...of
loop or the Symbol.iterator
method.
This protocol requires the object to have a Symbol.iterator
method, which returns an iterator object that can be used to iterate over the object’s values.
Here is the syntax to create an iterable object:
const myIterable = {
[Symbol.iterator]: function* () {
// yield values here
}
};
To iterate over an iterable object, you can use a for...of
loop:
for (let value of myIterable) {
// do something with each value
}
JavaScript iterable object example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const myIterable = {
[Symbol.iterator]: function* () {
yield 1;
yield 2;
yield 3;
}
};
for (let value of myIterable) {
console.log(value);
}
</script>
</body>
</html>
Output:
Here’s an example of an iterable object that returns the first five even numbers:
const evenNumbersIterable = {
[Symbol.iterator]: function* () {
let number = 0;
while (number < 10) {
number += 2;
yield number;
}
}
};
for (let number of evenNumbersIterable) {
console.log(number);
}
Do comment if you have any doubts or suggestions on this Js iterable topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version