JavaScript Iterables
Iterables are objects that can be iterated over with for...of
loops. Arrays, strings, sets, and maps are examples of built-in iterables in JavaScript.
Key Topics
- What Are Iterables?
- Built-in Iterables
- Creating Custom Iterables
- JavaScript Usage in DOM
- Key Takeaways
What Are Iterables?
An iterable is an object that implements the Symbol.iterator
method, returning an iterator that can produce values on demand.
Built-in Iterables
Arrays and strings are common iterables.
let arr = ["A", "B", "C"];
for (let element of arr) {
console.log(element);
}
Output
> A
> B
> C
Explanation: The array arr
is iterable, so for...of
directly accesses its elements.
Creating Custom Iterables
You can define your own iterables by implementing the Symbol.iterator
method that returns an iterator object with a next()
method.
JavaScript Usage in DOM
Iterables allow you to loop over collections (like DOM node lists or custom data) easily, extracting and displaying them in the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iterables in DOM</title>
</head>
<body>
<h1>Iterables Demo</h1>
<button onclick="showElements()">Show Array Elements</button>
<p id="output"></p>
<script>
function showElements() {
let items = ["Item1", "Item2", "Item3"];
let result = "";
for (let item of items) {
result += item + " ";
}
document.getElementById("output").textContent = result;
}
</script>
</body>
</html>
Key Takeaways
- Iterables: Objects that can be iterated with
for...of
. - Built-in Examples: Arrays, strings, maps, sets are all iterable.
- Custom Iterables: Define
Symbol.iterator
to create custom iteration logic. - DOM Integration: Easily loop through collections of elements or data for display.