JavaScript Secrets

Anonymous functions

Why anonymous functions are so very important: they can be used for various purposes such as event handlers, callbacks, methods for objects etc

// using anonymous function as event handler
button.onclick =
    function(){alert("hello portfour");};
// using anonymous functions as a method of an object
var port = {
    dock: function() {
          alert("Portfour is good for docking");
    }
};

port.dock();
// as a callback in an event handler

setTimeout(
    function(){alert("Ship leaves port in 500 milliseconds"); },
    500);

In the second example, even though the anonymous function is assigned a property named dock, the function does not acquire this name. To confirm this test for the function’s name property and you will find that it is still an empty string, not Null or undefined, but a string with length zero.

Recursion

The simplest definition is a self referencing function that converges toward termination. If it is self referencing but does not converge then you have an infinite loop!

// simple recusion, where a function returns a reference to itself
  function isPalindrome(text){
      if (text.length <= 1) return true;
      if(text.charAt(0) != text.charAt(text.length - 1)) return false;
   return isPalindrome(text.substr(1, text.length - 2));
}
// a simple function that counts backwards using recursion
function countDown(nbr){
  console.log("count is " +nbr);
  if (nbr > 1 ) {
   return countDown(nbr - 1); }
return false;
}

var port = {
   countDown: function(nbr){
              console.log("port count is " + nbr);
              if( nbr > 1 ) {
              this.countDown(nbr - 1)};
              return false;
};

}
port.countDown(7); // counts down from 7 to 1

run the code
The first example above shows recursion using a named function, that calls itself by name. This is a simple illustration of the concept, how about anonymous functions? How do you call something that has no name? Remember the example of anonymous functions used as methods? Well, since the method can be invoked using the property name, the anonymous function is also invoked this way. This allows you to call the method from another object property of the same name. The reference to the anonymous function still works even after the initial object has been reset and its properties no longer exist

var ship = {
    signal: function(n) {
            return n >1 ? this.signal(n-1) + "-beep" : "beep";
    }
};

var frigate = { signal: ship.signal };

ship = {};

if(frigate.signal(3) == "beep-beep-beep") alert("The method correctly calls itself");
alert(typeof ship.signal); // returns undefined

run the code

Inline named functions

What do you do when the methods have a different name from the property being referenced? The previous example only applies in a specific case where signal is the name used for both method and property. A more flexible approach would involve giving the anonymous function a name, this is called an inline function.

var port = {
    ship: function signal(n) {
       return n > 1 ? signal (n - 1) + "-beep" : "beep";
   }
};
if(port.ship(3) == "beep-beep-beep"){
   alert("Inline function recursion worked");
};

var frigate = { ship: port.ship };

port = {};
if(frigate.ship(3) == "beep-beep-beep"{
   alert("The inline function correctly calls itself");
};

Next post will look into functions as object and self-memoizing functions