JavaScript Iterables
8 April 2025 | Category: JavaScript
Iterables are data structures that can be looped through using the for...of
loop or other iteration methods.
In simple terms:
If you can use
for...of
on it, it’s an iterable.
✅ What Is an Iterable?
An object is iterable if it implements the Symbol.iterator
method.
✅ Built-in Iterables in JavaScript:
- Strings
- Arrays
- Maps
- Sets
- Typed Arrays
- NodeLists (like DOM elements returned by
querySelectorAll()
)
🧪 Example: Looping Through a String
let text = "Hello";
for (let char of text) {
console.log(char);
}
Output:
H
e
l
l
o
🧪 Example: Looping Through an Array
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
Output:
red
green
blue
🔧 How Iterables Work Under the Hood
Every iterable object has a default iterator method, which is accessed using:
object[Symbol.iterator]()
It returns an iterator object with a next()
method.
let arr = ["a", "b", "c"];
let iterator = arr[Symbol.iterator]();
console.log(iterator.next()); // { value: "a", done: false }
console.log(iterator.next()); // { value: "b", done: false }
console.log(iterator.next()); // { value: "c", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
🔄 Custom Iterable Example
You can create your own iterable objects by defining the [Symbol.iterator]()
method:
const myIterable = {
*[Symbol.iterator]() {
yield "Hello";
yield "World";
}
};
for (let value of myIterable) {
console.log(value);
}
Output:
Hello
World
🧾 Summary
Feature | Description |
---|---|
Iterable | Object you can loop over using for...of |
Examples | String, Array, Map, Set, etc. |
Custom Iterables | Can be created using [Symbol.iterator]() |
Use Case | Useful for loops, generators, async logic |