3 ms·
I usually go with a simple counter-generator as a first example: function counterMaker(next) { var value = next; return function() { value++; return
by BigZaphod 17y ago
I usually go with a simple counter-generator as a first example:
function counterMaker(next) {
var value = next;
return function() { value++; return value }
}
var myCounter = counterMaker(42);
alert(myCounter());
alert(myCounter());
alert(myCounter());
I'm not sure it is necessary to explain what they are/how they work right at the start. An example like this is pretty clear that something "weird" is going on and if "Joe" is interested at all, questions should probably come up which can then be answered with more details. I think the "what to use them for" stuff is going to depend quite heavily on the environment, language, libraries, and product you're working on.
I usually find it's better to introduce a language idea to someone and let them try to find out where they might put it on their own - they may surprise you. If you're doing code reviews, you could use that as an opportunity to point out how something like a closure (or any other construct) might have improved a situation, or, at least, how it may have changed it.