Thursday, September 28, 2017

Javascript Puzzle No.1 (beginner)

For few years I've been posting C# puzzles here, each puzzle was about a language feature or an unexpected semantics of some base class library methods. This post starts a new series, Javascript puzzles. Here's the first, easy one. Consider following generator function
function* foo()
{
    var n = 0;
    while ( true ) {
        yield n++;
    }
}
This seemingly creates an infinite enumeration of 0, 1, 2, etc. However, a simple test
for ( var i=0; i<10; i++ )
{
    console.log( foo().next().value );
}
reveals it doesn't really do what it's supposed to
0
0
0
0
0
0
0
0
0
0
The question here is to explain the incorrect behavior of the generator.

No comments: