DEV Community

loading...

Discussion on: Use-Cases For JavaScript Generators

Collapse
johannesvollmer profile image
Johannes Vollmer • Edited

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 ...
Enter fullscreen mode Exit fullscreen mode

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

Collapse
rfornal profile image
bob.js Author

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.