OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

When the right time to use [Symbol.iterator] in javascript?

  • Thread starter Thread starter Dananime
  • Start date Start date
D

Dananime

Guest
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?

Code:
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

<p>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?</p>
<pre><code>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
}
</code></pre>
<p>i hose someone tell me about this with easy explanation</p>
 

Latest posts

Top