Home > Web Front-end > Front-end Q&A > What are iterators and iterables in JavaScript?

What are iterators and iterables in JavaScript?

Robert Michael Kim
Release: 2025-03-18 13:51:32
Original
327 people have browsed it

What are iterators and iterables in JavaScript?

In JavaScript, iterators and iterables are fundamental concepts used for traversing collections of data, such as arrays, strings, and more complex data structures.

Iterables are objects that can be iterated over, meaning you can go through their elements one by one. An iterable in JavaScript must implement the @@iterator method, which is often symbolized as Symbol.iterator. When called, this method should return an iterator for the object.

For example, arrays and strings are built-in iterables in JavaScript. You can use the for...of loop directly on these to iterate over their elements:

const array = [1, 2, 3, 4, 5];
for (const value of array) {
    console.log(value); // Outputs: 1, 2, 3, 4, 5
}
Copy after login

Iterators, on the other hand, are objects that keep track of where you are in an iteration over an iterable. An iterator object must have a next() method, which returns an object with two properties: value, which is the next value in the sequence, and done, a boolean indicating whether the iteration has finished.

You can manually use an iterator like this:

const array = [1, 2, 3, 4, 5];
const iterator = array[Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
Copy after login

Understanding the distinction between these two concepts is crucial for effective data manipulation in JavaScript.

How can I use iterators to loop through an array in JavaScript?

You can use iterators to loop through an array by manually calling the next() method on the iterator object returned by the @@iterator method of an array. Here's a step-by-step example of how to do this:

const array = [10, 20, 30, 40, 50];
const iterator = array[Symbol.iterator]();

let result = iterator.next();
while (!result.done) {
    console.log(result.value); // Outputs: 10, 20, 30, 40, 50
    result = iterator.next();
}
Copy after login

This approach gives you fine-grained control over the iteration process. You can also use the for...of loop, which internally uses the iterator mechanism to loop through the array:

const array = [10, 20, 30, 40, 50];
for (const value of array) {
    console.log(value); // Outputs: 10, 20, 30, 40, 50
}
Copy after login

The for...of loop is a more convenient and commonly used way to iterate over iterables.

What is the difference between an iterable and an iterator in JavaScript?

The primary difference between an iterable and an iterator in JavaScript lies in their roles and functionalities during the iteration process.

  • Iterable: An iterable is an object that represents a collection of data and can be iterated over. It has a Symbol.iterator method, which returns an iterator. The purpose of an iterable is to provide a way to access its elements sequentially.
  • Iterator: An iterator is an object that facilitates the actual process of iteration. It keeps track of the current position in the iteration and provides the next() method to retrieve the next element in the sequence. Each call to next() returns an object with value and done properties.

Here's a simple illustration of these concepts:

// An array is an iterable
const array = [1, 2, 3];

// Getting an iterator from the iterable
const iterator = array[Symbol.iterator]();

// Using the iterator
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Copy after login

In summary, an iterable provides the mechanism to get an iterator, while the iterator performs the iteration by producing successive elements of the iterable.

Can you provide examples of built-in iterables in JavaScript?

JavaScript includes several built-in data types that are iterables. Here are some examples:

  1. Arrays:
    Arrays are one of the most commonly used iterables in JavaScript. You can use the for...of loop to iterate over the elements of an array.
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
    console.log(fruit); // Outputs: apple, banana, cherry
}
Copy after login
  1. Strings:
    Strings are also iterables, where each iteration yields a character in the string.
const message = "Hello";
for (const char of message) {
    console.log(char); // Outputs: H, e, l, l, o
}
Copy after login
  1. Maps:
    Maps are iterable collections of key-value pairs. The for...of loop iterates over the key-value entries.
const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (const [key, value] of map) {
    console.log(key, value); // Outputs: a 1, b 2, c 3
}
Copy after login
  1. Sets:
    Sets are collections of unique values and are iterable. The for...of loop iterates over the values in the set.
const set = new Set([1, 2, 3, 4, 5]);
for (const value of set) {
    console.log(value); // Outputs: 1, 2, 3, 4, 5
}
Copy after login

These built-in iterables make it straightforward to handle collections of data in JavaScript using the iteration mechanisms provided by the language.

The above is the detailed content of What are iterators and iterables in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template