Categories

JavaScript Closure Syntax

Most documentation regarding JavaScript closures is overly complex and, in my opinion, does a poor job of explaining their use well; so here’s my attempt to dumb it down a little. Here’s the basic syntax for a JavaScript closure.

The purpose of a closure is to allow a variable to maintain its scope when called in the future. This is a common scenario in loops, where a variable needs to be passed to an event handler, but the same variable is updated multiple times during the loop.

For example, imagine that you want to add a mouseover handler to every <a> element on your page so that when the user hovers over a link, the title attribute is displayed as a custom-styled tooltip.

Unfortunately, the above code will not work, and the same tooltip will display over every link. That’s because the tooltip variable continues to be updated until the end of the loop, and you end up passing its last updated value to the showTooltip() function when the mouseover event is triggered.

Closures work by using an anonymous function to return a new function with a new scope for the variable. Here’s how the code above can make use of a closure to retain the appropriate value of the tooltip.