The [Symbol.iterator]
property is a unique feature in JavaScript that transforms any object into an Iterable. For instance, an Array, being an Iterable object, naturally possesses this property.
The primary function of the [Symbol.iterator]
property is to provide an Iterator object with the next()
method. This Iterator allows you to traverse through the Array or data within the Iterable Object.
You also have the ability to create your own custom Iterable object, enabling you to acquire an Iterator by executing its [Sysmbol.iterator] method. This specific syntax []is introduced in ES6, allowing you to utilize any Symbol
as a method name within a class, referred to as computed property.
The following code snippet illustrates how you can implement [Symbol.iterator]
as a method name to establish your personal iterable object. While this example offers a basic demonstration on utilizing [Symbol.iterator]
, there exist alternative methods to achieve the same outcome:
class CustomIterable{
constructor(start, stop){
this.start = start;
this.stop = stop;
}
//Defining [Symbol.iterator] makes it Iterable
[Symbol.iterator](){
return this;
}
//This also defines it as an Iterator
next(){
return this.start !== this.stop ? {value: this.start++, done: false}
: {value: this.stop, done: true};
}
}
const cutomIterable = new CustomIterable(0, 11);
console.log(cutomIterable[Symbol.iterator]().next().value);
//This object supports the for..of loop
for( let val of cutomIterable){
console.log(val);
}