re: Use-Cases For JavaScript Generators VIEW POST


The first example can be done using just a simple plain old function. Why would you use generators for that?

function idCreator() {
  let i = 0;
  return () => i++;

const nextId = idCreator();

console.log(nextId()); // 0
console.log(nextId()); // 1
console.log(nextId()); // 2
// etc ...

It's even less code than the generator example. I'm sure the other examples can be done without generators too.


This article was more about the generators ... and how they can be used, not proving it better or worse than traditional methods. The idea wasn't to come up with examples that couldn't be done in regular JavaScript. The idea was to come up with examples of practical generator usage.

Yes, some of these examples can be done in Vanilla JS. But, given the generator's ability to be a "state machine," it can provide a more elegant solution in a few cases ... although, again, that was not the focus of the article.

code of conduct - report abuse