Symbol.iterator Explained: Become a JavaScript Iteration Pro with Symbol.iterator

Awwfrontend
2 min readMar 4, 2023

--

Abstract

If you’re working with JavaScript, chances are you’ve come across the Symbol.iterator symbol before. But what exactly is Symbol.iterator and how does it work? In this post, we'll dive into the world of JavaScript iterators and explore how you can use Symbol.iterator them to make your code more efficient.

If you prefer to learn by watching, check out the following video first.

https://youtu.be/JhELIsF3ANc

Otherwise, read on to learn more!

JavaScript is a powerful programming language that allows developers to create complex applications for the web. One of the most important concepts in JavaScript is iteration — the ability to loop over collections of data and perform actions on each item.

In order to support iteration, JavaScript has a built-in symbol called Symbol.iterator. This symbol represents the default iterator for an object and allows you to access its values one at a time.

For example, if you have an array of numbers, you can use the Symbol.iterator symbol to loop over the values of the array like this:

const numbers = [1, 2, 3];

for (const num of numbers) {
console.log(num);
}

Under the hood, the for...of loop is using the default iterator of the numbers array to access its values one by one.

So how does the default iterator work? Essentially, the default iterator for an object is a function that returns an object with a next() method. This next() method returns an object with two properties: value and done. The value property is the current value of the iterator, while the done property indicates whether the iterator has reached the end of the collection.

In addition to the default iterator, you can also create custom iterators using Symbol.iterator. Here's an example of how to create a custom iterator for an object:

const myObject = {
data: [1, 2, 3, 4, 5],
[Symbol.iterator]() {
let index = 0;
const data = this.data;
return {
next() {
if (index < data.length) {
return { value: data[index++], done: false };
} else {
return { done: true };
}
}
};
}
};

for (const value of myObject) {
console.log(value);
}

In this example, we’re creating a custom iterator for the myObject object that returns the values of its data property. We're using the Symbol.iterator method to define our custom iterator and return an object with a next() the method that returns the values of the data property one at a time.

In conclusion, Symbol.iterator is a powerful tool that can make iterating over collections in JavaScript more efficient and streamlined. Whether you're working with arrays, sets, maps, or custom objects, Symbol.iterator can help you loop over your data with ease. We hope this post has helped you understand the basics of Symbol.iterator and how it works.

Thank you!

--

--