JavaScript – The Good Parts – Part 4

Introduction

This is the fourth post based on the book JavaScript – The Good Parts by Douglas Crockford. The previous post covered some features of functions in JavaScript. This post takes this forward and covers more features of functions in JavaScript. The key concepts are Closures and Inner Functions which are very powerful features available to programmers of JavaScript.

Closure and Inner Functions

The “inner functions” get access to all variables and parameters of the function they are defined within, with the exception of “this” and “arguments”. We saw example of this in the previous post. Since a function is also a variable in JavaScript the values of the variables in a JavaScript function remains with the function for the lifetime of the function. A lifetime of the function depends on how the function is invoked. When a function is declared in the global scope and is invoked the lifetime of the function is limited to its execution time. Once the function is executed the function dies. When a function is used to create an object the lifetime extends to the lifetime of the variable. If this variable is at a global level then the lifetime of the function is equal to the lifetime of the document. When a function is passed as a variable to another function, the lifetime of the function extends to the lifetime of the function that is being invoked. The function carries with it any values within it. Consider a situation where we need to walk through all the nodes in the DOM of an HTML and invoke a function on the element. We need to recursively move through the elements and it is children and invoke the function on each of the element.

What is being done is that Counter function returns an object which contains the increment and decrement functions, but the outside world cannot access the currentValue variable. We can now instantiate counters as.

In a similar manner we can hand hide functions. Any function that is not returned as part of the object will be private to the global function and can be accessed from anywhere within that function.

Using setTimeout with Closure

Consider a use case where it is required to fade out a node slowly over a period of time. One will need to use the setTimeout function of JavaScript to slowly reduce the opaqueness of the node. But the problem that arises is how to keep the value of the node between two calls invoked by setTimeout. The easiest way out is to define a global variable which has this node and the setTimeout will function on this global variable. But what if one needs to fade out more than one node at a time? This can be solved elegantly by using closure as given below: