1.1 Basic Concepts
Iterables and iterators in JavaScript are core concepts that allow objects to be looped over. These concepts are widely used in modern JavaScript, especially in constructs like for...of
loops, the spread operator, destructuring, and many others. In this lecture, we'll go over what iterables and iterators are, how they work, and how to create and use them.
Iterables
Iterables are objects that implement the iteration protocol. They must have a special method with the key
[Symbol.iterator]
, which returns an iterator object.
Iterators
An iterator is an object with a next()
method, which returns an object with two properties:
value
— the value of the next element in the sequencedone
— a boolean indicating whether the sequence has finished (true
) or not (false
)
Let's check out some examples of usage.
Built-in Iterables
JavaScript has several built-in iterables, including arrays, strings, Set
objects, and Map
objects.
Example 1: Iterating over an Array
const array = [1, 2, 3, 4, 5];
for (const item of array) {
console.log(item);
}
// Outputs: 1 2 3 4 5
Example 2: Iterating over a String
const string = 'hello';
for (const char of string) {
console.log(char);
}
// Outputs: h e l l o
1.2 Creating Your Own Iterators
You can create your own iterator by implementing the iteration protocol — creating a next()
method.
Example 1: Creating an Iterator
function createIterator(array) {
let index = 0;
return {
next: function() {
if (index < array.length) {
return { value: array[index++], done: false };
} else {
return { done: true };
}
}
};
}
const myIterator = createIterator([1, 2, 3]);
console.log(myIterator.next()); // { value: 1, done: false }
console.log(myIterator.next()); // { value: 2, done: false }
console.log(myIterator.next()); // { value: 3, done: false }
console.log(myIterator.next()); // { done: true }
Creating Iterables
To make an object iterable, it must implement the [Symbol.iterator]
method. Yeah, it's got a fancy name. Here's how to create one.
Example 2: Creating an Iterable
const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
};
for (const value of myIterable) {
console.log(value);
}
// Outputs: 1 2 3
1.3 Built-in Methods
Let's look at built-in methods and operators for working with iterables.
Example 1: The Spread Operator
The spread operator (...
) can be used to copy or concatenate iterables.
const array = [1, 2, 3];
const newArray = [...array, 4, 5, 6];
console.log(newArray); // Outputs: [1, 2, 3, 4, 5, 6]
Example 2: Destructuring
Destructuring lets you extract values from iterables.
const [first, second, third] = [1, 2, 3];
console.log(first); // Outputs: 1
console.log(second); // Outputs: 2
console.log(third); // Outputs: 3
Example 3: Array.from and Array.of Methods
The Array.from()
method lets you create an array from an iterable.
const set = new Set([1, 2, 3, 4, 5]);
const array = Array.from(set);
console.log(array); // Outputs: [1, 2, 3, 4, 5]
GO TO FULL VERSION