What is Symbol.iterator in JavaScript: Explained with Examples
Symbol.iterator is a built-in JavaScript symbol that defines the default way an object is iterated over in loops like for...of. It is a key that points to a method returning an iterator, which controls how the object’s values are accessed one by one.How It Works
Imagine you have a box full of items and you want to look at each item one by one. Symbol.iterator is like a special key that tells JavaScript how to open that box and get each item in order.
When you use a for...of loop or other iteration methods, JavaScript looks for the Symbol.iterator method on the object. This method returns an iterator, which is like a helper that knows how to give you the next item each time you ask.
This system lets JavaScript work with many different types of objects in a consistent way, whether they are arrays, strings, or custom objects you create yourself.
Example
This example shows how an array uses Symbol.iterator to loop through its values with for...of.
const arr = [10, 20, 30]; // Get the iterator from the array const iterator = arr[Symbol.iterator](); console.log(iterator.next()); // { value: 10, done: false } console.log(iterator.next()); // { value: 20, done: false } console.log(iterator.next()); // { value: 30, done: false } console.log(iterator.next()); // { value: undefined, done: true } // Using for...of loop for (const value of arr) { console.log(value); }
When to Use
You use Symbol.iterator when you want to make your own objects work with loops like for...of or spread syntax (...).
For example, if you create a custom collection or data structure, adding a Symbol.iterator method lets others easily loop through your data just like they do with arrays.
This is useful in real-world cases like reading data streams, processing sequences, or creating libraries that handle collections of items.
Key Points
- Symbol.iterator is a special key for the default iterator method.
- It returns an iterator object with a
next()method to get values one by one. - Objects with
Symbol.iteratorcan be used infor...ofloops and spread syntax. - You can define
Symbol.iteratoron your own objects to make them iterable.
Key Takeaways
Symbol.iterator defines how an object is looped over in JavaScript.next() method.Symbol.iterator by default.Symbol.iterator to your own objects to make them work with for...of loops.Symbol.iterator helps create flexible and consistent ways to access data.