The evil closure explained

March 5th 2013 by Samuel Rossille

Everybody has fallen at least once into this pitfall:

for(var i = 0; i < books.length; i++) {
    doAsync(function() {
        var book = books[i];

        readBook(book); // BIG BADABOUM CRASH 
        // i is books.length
        // book is undefined
    });
}

So what happened ? Now imagine you are a CPU. Mother earth is generous:

Wouldn't that be cool? But unfortunately everything has a price and you don't have a will of your own.

So all you can do is executing endless to-do-lists written by others or by yourself (because sometimes the current instruction on your to-do-list is to write a to-do-list). Maybe not so cool actually... But cheer up; we have a pretty bookshelf here: the-evil-closure-explained-bookshelf Now get to work! As a CPU, you are bound to execute your todo list, which is:

1. Look at this bookshelf in front of you.
2. Put this button on the shelf in front of the leftmost book.
3. Is the button in front of a book? Yes -> go to step 4, No -> go to step 8
    4. Take a blank sheet of paper and write the following text:

        |-----------------------------------------------------------------------|
        |                                                                       |
        |  1. From the bookshelf, take the book that's in front of the button.  |
        |  2. Read the book.                                                    |
        |                                                                       |
        |-----------------------------------------------------------------------|
    5. Go put this paper in your mailbox.
    6. Push the button of "one book thickness" to the right.
    7. Go to step -> 3.
8. Now go to your mailbox
9. Is there a paper in the mailbox? Yes -> go to step 10. No -> go to step 13
    10. Read the paper
    11. Do exactly what's written on the paper.
    12. Once you are done with what was on the paper, throw it away and go to step 9.
13. You're done for today. Dismissed!

What happens when you execute this program, especially at step 11? Do you see the similarity with the code above?

That's the problem of the evil closure inside the loop! But how to solve it ? To be continued...