Js Iterables in JavaScript
? JavaScript Iterables
Iterables are objects that can be looped over (iterated) using constructs like for...of. This includes data structures such as arrays, strings, maps, sets, and more.
? What Is an Iterable?
An iterable is any object that implements the Symbol.iterator method and returns an iterator.
? Common Built-in Iterables:
| Iterable Type | Example |
|---|---|
| Array | [1, 2, 3] |
| String | "hello" |
| Set | new Set([1, 2, 3]) |
| Map | new Map([[1, "a"]]) |
| NodeList | document.querySelectorAll("p") |
? Example 1: Iterating an Array
const fruits = ["apple", "banana", "cherry"];for (let fruit of fruits) { console.log(fruit);}? Example 2: Iterating a String
const text = "JS";for (let char of text) { console.log(char); // J then S}? Example 3: Custom Iterable
You can create your own iterable object:
const myIterable = { *[Symbol.iterator]() { yield 1; yield 2; yield 3; }};for (let value of myIterable) { console.log(value);}? Differences: for...of vs for...in
for...of | for...in |
|---|---|
| Iterates values of iterables | Iterates keys of objects (or arrays) |
| Used with arrays, strings, etc. | Used with objects |
? Use With Spread and Destructuring
const nums = [1, 2, 3];const copy = [...nums]; // Spread operator with iterableconsole.log(copy); // [1, 2, 3]Would you like examples of iterating Maps, Sets, or creating your own iterator?