Nice article :)<p>The thing that helped me understand closures was really thinking about <i>why</i> they're confusing for beginners.<p>For example, let's say you show the following code to someone who's never heard of closures, and ask them what it should do.<p><pre><code> var foo = 0;
var f = function() {
return foo;
}
f();
</code></pre>
The thing that's confusing to beginners here is that <i>there is no right answer</i> to this question, and yet by being asked the question, you feel like you should be able to intuit the "right" behavior. For example, the previous code returns 0, but the analogous code will break in Ruby:<p><pre><code> foo = 0
def f
foo
end
f # => NameError: undefined local variable or method `foo' ...
</code></pre>
And then you say, er, Ruby does closures too:<p><pre><code> foo = 0
define_singleton_method :f do
foo
end
f # => 0
</code></pre>
How to handle this situation is up to the programming language: it might break, or it might use dynamic scope, or it might use closures/lexical scope (any others?).<p>Closures are initially confusing not because they're a difficult topic, but because their entire existence hinges on a programming language design decision that you, as a beginner, know nothing about. You can't see it in the text of the program. I think that if you clarify up front that someone, back in the day, realized that it would be pretty cool if languages worked liked <i>this</i>, instead of like <i>that</i>, then it makes understanding closures a lot easier.