Removing Noise With Yield

Learn about the yield keyword and how you can use it to remove noise.

Introduction

Let’s put the role of the iterator method, introduced in the previous lesson into words. As the caller iterated over the object, the iterator yielded the next value. To achieve that, we wrote quite a bit of code. We can get rid of most of the extraneous code using the special yield keyword.

Using yield

The caller of the iterator function should know if it should merely expect an object with the next() function or if it should do some extra work to process the result returned by yield. To help guide the caller, JavaScript relies on a special syntax; if the iterator will use yield, the method should be decorated or marked with a *.

yield in action

Let’s convert the iterator method’s implementation from using the object with next(), as shown in the previous lesson, to a much more fluent and concise version using yield.

Get hands-on with 1200+ tech skills courses.