In Use JavaScript Generators

In Use JavaScript Generators

What is a Generator in JavaScript?

Generator is a multiple things in one:

  • Function that can return a multiple values;
  • Its declaration is followed by an asterisk (like `function* helloWorld() {}`)
  • It uses `yield` keyword to pause and resume itself
  • It conforms to both the iterable protocol and the iterator protocol.


Where and how I can use it?

So, your client asked you to add a button such that when you click on it the text of that button should be changed from red to green, from green to blue and then start over - from blue to red -> green -> blue -> red -> green -> blue -> red... Okay, you got it.

Just think for a sec how'd you implement such thing? And then take a look at implementation with generators. It's really that easy (click on image to get the code).

colorPaletteGenerator

Isn't that cool? Btw, if you work with React-Saga you should know that they use Generators under the hood.

And what things do you use the generators for?

Jason Welsh

Frontend Engineer at GroupBy Inc.

4 年

I never used generators until using Redux Saga. Yielding the execution of a function so that your code reads procedurally is a great feature

要查看或添加评论,请登录

Serhii Kucherenko的更多文章

社区洞察