Function handling in Javascript is a rather different affair than in  most other languages.

Firstly, Javascript treats functions as variables, which in itself is a different way of thinking to other languages. This has the side effect of allowing functions to be defined within functions, which then limits their scope.

The side effect of that side effect is that while Javascript does not have true classes as in other object orientated languages, classes can be simulated by defining functions and variables inside of a function, which I spoke about in my previous post.

Another side effect of treating functions as variables is that it enables you to pass a function as an argument to another function. This is known as a lambda function, and one of the coolest features of Javascript.

The advantages of using lambda functions is that when using conventional functions, underlying variables are accessible to other functions and all manner of interesting bugs can creep in as functions in Javascript are executed asynchronously. Lambda functions, however, create a new instance of all variables it creates and are not able to be affected by outside influences, so the function will always run as expected.

To create a lambda function all you need to do is this:

   var str = "Hello ";

   var displayMessage = (function(msg1){
      return function(msg2){
         alert(msg1 + msg2);
      }   
   }(str));

This creates a lambda function and passes a parameter which is visible within the lambda function (in this case, msg1 which is passed str as its value). This function then returns a function with the parameter msg2.

You then call the function by

   displayMessage("World");

This then passes the value “World” into the msg2 parameter, and within the function, the function has access to both msg1 and msg2. If the original values outside the function are changed, then msg1 and msg2 are unaffected as local instances are created of the parameters.

It might be a little strange at first, but I’ve known how to do this only a few days and already I am finding many uses for this type of function.

This is one of the reasons why I am starting to fall in love with Javascript. It allows me to do things I never thought imaginable.

Share