1

I am working on now, and I am looking at the Google Maps API.

In many examples, I find that functions are defined in a way that is really strange to me.

google.maps.event.addListener(marker, 'click', function() {
    // do stuff
});

I tried to use the approach that I have learned before and define my functions as

google.maps.event.addListener(marker, 'click', myFunction(myParameter));

function myFunction(myParameter)
{
    // do stuff
}

But it doesn't work which is confusing.

5

Two different things here:

  1. there is a function
  2. and there is a function call

In JavaScript, functions are so-called first-class objects, and what this means is that they, like other values, can be passed to or returned by other functions.

So it is possible for a JavaScript function to take another function as an argument (or return another function), as it's the case with addListener—it takes a function that gets called when the specified event is fired.

You can pass functions to other functions using their names (e.g., foo(bar)—where bar is another function (not a function call) defined somewhere and is in scope), or you can pass anonymous functions—functions without names (ideally when the function is used once).

And then there's a function call (the one with the parentheses and possibly parameters), which is an expression that may return some value, as we're familiar.

For more clarity, consider the following example:

/**
 * @returns {Number} the value 50
 */
function getFifty() {
    return 50;
}

/**
 * @returns {Number} the value 42
 */
function getFortyTwo() {
    return 42;
}

/**
 * Sums the return values of two functions each of which returns a number
 *
 * @param {Function} func1 the first function that returns a number
 * @param {Function} func2 the second function that returns a number
 * @returns {Number} the sum of the return values of the passed functions
 */
function sumFuncs(func1, func2) {
    // call func1 and func2 and return the sum of the results
    return func1() + func2();
}

/**
 * Sums two numbers
 * 
 * @param {Number} val1 the first number
 * @param {Number} val2 the second number
 * @returns {Number} the sum of the passed two numbers
 */
function sumVals(val1, val2) {
    return val1 + val2;
}

// pass functions (don't call them—sumFuncs does that for us)
var sum1 = sumFuncs(getFifty, getFortyTwo); // stores 92

// pass values (i.e., the return values of the two function calls)
var sum2 = sumVals(getFifty(), getFortyTwo()); // stores 92

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .