Matt Matt - 3 months ago 11
Javascript Question

What exactly is the difference between these two javascript functions?

I've come across two types of functions whilst learning javascript I think. I've tried to put them below as I understand them.

function example(arg1, arg2) { //code to do stuff here }


and

thing.method(function(arg) {
//code to do stuff here
});


My thinking is that the first case is creating a function called example which takes two arguments and stuff happens in the curly brackets. I believe the function can be called and used as long as it is in scope (I think that's the correct word?).

In the second I get confused. My thinking is that we have a thing (an array, object, whatever) a method gets called on that thing (foreach, map, etc) then I get stuck. There is a function, which doesn't have a name? Takes one argument and stuff happens within the curly brackets. Lets say the thing was an array and we called foreach then the stuff inside the function brackets would happen to each element? Why would I use this rather than just creating a function like the first one which I could just call?

Why couldn't I just say:

function example(arg) { //stuff }
thing.method(example(arg));


I may have misunderstood a few things. Would somone be able to clear things up for me?

Answer
thing.method(function(arg) {
  //code to do stuff here
});

This uses what is called an anonymous function. Like you said, it has no name. It is passed as an argument to thing.method(). thing.method()'s function body would use this function such as:

thing: {
    method: function(callback) {
        //...
        callback();
        //...
    }
};

You cannot write this as

function example(arg) { /* stuff */ }
thing.method(example(arg));

because in this example you are passing the return value of example(arg) into thing.method(), instead of the function itself. You could, however, write it like this:

function example(arg) { /* stuff */ }
thing.method(example);

Now, you could picture method() setting some variable and passing it to the function that you passed in, such as:

thing: {
    method: function(callback) {
        var foo = "bar";
        //...
        callback(foo);
        //...
    }
};