so im learnig javascript and i found about [Symbol.iterator], i don’t know what is this, when to use it and why we use it?
class CustomRange {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
let current = this.start;
let end = this.end;
return {
next() {
if (current <= end) {
return { value: current++, done: false };
} else {
return { value: undefined, done: true };
}
}
};
}
}
let range = new CustomRange(1, 5);
for (let num of range) {
console.log(num); // 1 2 3 4 5
}
i hose someone tell me about this with easy explanation