JavaScript Iterables
In JavaScript, iterables are objects that allow iteration over their elements. They provide a standardized way to access elements sequentially, enabling the use of `for...of` loops and other iteration techniques. Common iterables include arrays, strings, maps, and sets.
1. What is an Iterable?
An object is considered iterable if it implements the iterable protocol. This protocol requires the object to have a method with the key `[Symbol.iterator]` that returns an iterator object. An iterator object must have a `next()` method that returns objects with the format `{ value, done }`:
// Example of an iterable object
const iterable = {
[Symbol.iterator]: function() {
let step = 0;
const iterator = {
next: function() {
step++;
return { value: step, done: step > 5 };
}
};
return iterator;
}
};
for (let value of iterable) {
console.log(value);
}
// Output: 1 2 3 4 5
2. Built-in Iterables
JavaScript provides several built-in iterables that you can use directly:
Arrays
// Array iteration example
const numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
// Output: 1 2 3 4 5
Strings
// String iteration example
const str = "hello";
for (let char of str) {
console.log(char);
}
// Output: h e l l o
Maps
// Map iteration example
const map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Output: key1: value1 \n key2: value2
Sets
// Set iteration example
const set = new Set([1, 2, 3, 4, 5]);
for (let item of set) {
console.log(item);
}
// Output: 1 2 3 4 5
3. Custom Iterables
You can create your own iterable objects by implementing the iterable protocol. Here’s how you can define a custom iterable object:
// Custom iterable object example
const customIterable = {
[Symbol.iterator]: function() {
let count = 0;
return {
next: function() {
count++;
return { value: count, done: count > 3 };
}
};
}
};
for (let value of customIterable) {
console.log(value);
}
// Output: 1 2 3