views:

899

answers:

2

I heard about a "yield" keyword in javascript, but i found very poor documentation about it. Can someone explain me (or recommend a site that explains) its usage and what it is used for?

+4  A: 

It's used for iterator-generators. Basically, it allows you to you to make a (potentially infinite) sequence using procedural code. See Mozilla's documentation.

Matthew Flaschen
+4  A: 

The MDC documentation is pretty good, IMO.

The function containing the yield keyword is a generator. When you call it, its formal parameters are bound to actual arguments, but its body isn't actually evaluated. Instead, a generator-iterator is returned. Each call to the generator-iterator's next() method performs another pass through the iterative algorithm. Each step's value is the value specified by the yield keyword. Think of yield as the generator-iterator version of return, indicating the boundary between each iteration of the algorithm. Each time you call next(), the generator code resumes from the statement following the yield.

Matt Ball