Fun with Closures

This counter uses a global variable to keep track of the current number.

It appears to work well. Try it and see...

There is a problem with using a global variable however. The problem is that any script on the page can change the global count variable.

See what happens when the wrong script affects the counter...

Since JavaScript does not include private properties closures must be used.

A closure is when there is a function within a function. The inner function has access to the outer function's variables. There are no other functions that have access to these variables.

This counter uses a closure which simulates a private variable


This doubling counter also uses a closure which simulates a private variable


This calculator has an outer function which receives an operator as a parameter and has an inner function (which does the calculation) that receives two operands as parameters.

For more information and helpful links, visit my blog entry