chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Iterator and Generator in ES6

2017-07-19

Iterator and Generator are commonly used features in ES6. In this post, we will walk through the key features of iterator and generator in depth.

Iterator

In JavaScript, an object can be iterated due to it has an inner-built property/object: iterator (which objects?). So in order to let an ordinary object can be iterator, we can add iterator to this object manually.

[gist https://gist.github.com/arkilis/3e18e939aa527c41a4c3acbe5bf918e9/]


Generator

Generator functions are functions defined with *. They are can be treated as special functions that using keyword yield to return iterator objects.

[gist https://gist.github.com/arkilis/94f5a59c65212b99419d07cace3ec561]

With generator return {done: false, value: "Sam"}, we can shorten the our man-crafted iterable object user as following:

[gist https://gist.github.com/arkilis/2a27da00b6f7a55f0329990e0e667418/]


Reference

  1. CodeSchool
  2. http://www.arkilis.me

arkilis

Comments: