JavaScript Essentials - Iterators
Understanding and implementing iterators
Iterators are a fundamental part of JavaScript that enable you to traverse through a collection of items, such as arrays or objects. This tutorial covers the basics of iterators, how they work, and how to implement them.
Key Points:
- An iterator is an object that provides a sequence of values.
- The
next()
method is used to get the next value in the sequence. - Iterators are useful for custom traversal algorithms.
Basic Iterator
An iterator object in JavaScript implements the Iterator
protocol by having a next()
method that returns an object with two properties: value
and done
.
function createIterator(array) {
let index = 0;
return {
next: function() {
if (index < array.length) {
return { value: array[index++], done: false };
} else {
return { done: true };
}
}
};
}
const iterator = createIterator([1, 2, 3]);
console.log(iterator.next()); // Output: { value: 1, done: false }
console.log(iterator.next()); // Output: { value: 2, done: false }
console.log(iterator.next()); // Output: { value: 3, done: false }
console.log(iterator.next()); // Output: { done: true }
Built-in Iterables
JavaScript provides several built-in iterables, such as arrays, strings, and maps. These iterables have a default iterator method that returns an iterator object.
const array = [10, 20, 30];
const iterator = array[Symbol.iterator]();
console.log(iterator.next()); // Output: { value: 10, done: false }
console.log(iterator.next()); // Output: { value: 20, done: false }
console.log(iterator.next()); // Output: { value: 30, done: false }
console.log(iterator.next()); // Output: { done: true }
Custom Iterators
You can create custom iterators for your own objects by implementing the [Symbol.iterator]()
method, which should return an iterator object.
const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
};
for (const value of myIterable) {
console.log(value); // Output: 1, 2, 3
}
Use Case: Fibonacci Sequence
Here is an example of creating a custom iterator to generate the Fibonacci sequence:
const fibonacci = {
[Symbol.iterator]() {
let [prev, curr] = [0, 1];
return {
next() {
[prev, curr] = [curr, prev + curr];
return { value: prev, done: false };
}
};
}
};
const fib = fibonacci[Symbol.iterator]();
console.log(fib.next().value); // Output: 1
console.log(fib.next().value); // Output: 1
console.log(fib.next().value); // Output: 2
console.log(fib.next().value); // Output: 3
console.log(fib.next().value); // Output: 5
Summary
In this tutorial, you learned about iterators in JavaScript, including how to create and use basic and custom iterators. Understanding iterators helps you create custom traversal algorithms and work effectively with collections of data.