Next page | Contents page |

Function literals

We have already seen an example of a function being declared with no name in order to attach it to a prototype to become a method.

Anonymous functions can be created for other reasons. Eg,

  a[3] = function (x) { return x * x; };
             //  ^ no name, only parameter x

defines a value of type Function and assigns it to a[3]. Then we could invoke the function with, eg:

  var tensquared = a[3](10);

This example uses an array element deliberately to look odd. Always avoid such cleverness in real code, for maintainability. However it can sometimes be useful and it is another thing which is exploited in some JavaScript libraries (eg, jQuery).

Next page | Contents page |