Another great question from a reader of Head First HTML5 Programming is about passing functions as values. This comes up when using the Geolocation API: the way you get your location is to call the built-in function getCurrentPosition() and pass in two arguments, both of which are functions. The reader asks:

When you call getCurrentPosition(displayLocation, displayError), how are you able to call the function displayLocation() from within the parameters of this method, and when you call it, how does it know to how to pass the position object to displayLocation() when you didn’t pass any parameters when you called it?

When you write getCurrentPosition(displayLocation, displayError), you are not calling the displayLocation and displayError functions, you are passing them as values! I know it seems odd to pass a function as a value, but that is actually one of the powerful things about JavaScript (not all programming languages allow you to do this!). Think of the parameters displayLocation and displayError as names for values, just like any other parameter that expects a value (whether that’s a number, a string, an object, or a function!). Because getCurrentPosition() is a function built-in to JavaScript (and part of the Geolocation API), rather than one you write yourself, you don’t see getCurrentPosition() actually calling those functions. If you could see inside getCurrentPosition(), you’d see it call one of the functions, say displayLocation(position), and of course it would be passing in your position (as an object).

You can write your own functions that take other functions as arguments. For example:

function f(g) { 
  return g(1); 
}

function add1(x) {
  return x + 1;
}

f(add1);

You’ll get 2. Kind of mind-bendy, right? So what’s happening here is that you are creating two functions: add1 takes a number, x, and adds 1 to it and returns it. Function f takes a function, which you give the name g. f calls g, and passes a number, 1, into it.

So, when you pass the function value add1 to f, f uses the parameter name g as the name for the function value (remember, JavaScript is pass by value!!) and calls g, with the result that you get the number 2.

This topic of functions as values and passing functions to other functions is quite complex and deserves a more in-depth treatment for sure, and we just didn’t have room in Head First HTML5 Programming to delve into it. We’ll have to tackle that in an in-depth tutorial at some point! Let us know if that’s a topic you’d be interested in learning more about.

Don't miss out!!

Don't miss out on brain-friendly WickedlySmart updates early access to books and general cool stuff! Just give us your email and we'll send you something about once a week. 

You have Successfully Subscribed!