Putting function in Javascript function arugments?


#1

I’ve been writing scripts in python to automate stuff forever so I understand how to declare a function just fine and all, but Javascript has a really weird, really confusing convention that I can’t seem to grasp, nor do I know what it’s called so my google-fu hasn’t come up with anything.

myfunction(arg1, arg2, function(err, data){
    /* wtf? */
});

I don’t understand WHAT function is being called. Is one being called, or declared? I don’t understand this convention in the slightest and most of the google results I’ve gotten have had to do with explaining that err is the first argument. I LOVE the algorithm challenges but this has left me screeching to a grinding halt in my progress. Can anyone explain or rubber duck this for me? No matter how many times I retry the old challenges or google it I can’t make sense of this.


#2

In the code you posted:

  • An “anonymous” function is created (the function that takes err, data)
  • myfunction is called with 3 arguments:
    • arg1
    • arg2
    • The anonymous function
  • The anonymous function will probably be called once myfunction has finished doing its thing.

Let me tweak/expand your example code a little further:

function myfunction(word1, word2, callback) {
  const phrase = word1 + ' ' + word2 + '!';

  callback(phrase);
}

myfunction('hello', 'world', function(data){
    console.log(data);
});

The above will log hello world!

Functions that are passed as arguments are generally called “callbacks” because they’re usually called once the first function has finished its execution. Note however that the function argument doesn’t have to be called ever.

You can also name these functions if you want (and some people think these functions should always be named).

In your example, myfunction might call the function after pulling some data from a database or making an HTTP request. In that case, the callback function receives an err argument, which will (most likely) be null if the request was successful, and will contain error information if an error occurred.

It’s worth noting that the err, data convention is just a convention, but a lot of things follow it so you’ll see it a lot.

Let me know if that didn’t quite clear things up. Callbacks are a nice feature but I’ll admit they are a little weird.

Edit: By the way, here’s an article I found on callback functions.

Check out @ppc’s reply below for a more concise answer than the article offers.


#3

Both JavaScript and Python treat functions as first-class objects. Below is an example in Python like the JavaScript example you posted. You can pass functions as arguments.

def a():
  print('hello')

def b(arg1, func):
  func()
  print(arg1)

b('goodbye', a)

The above code produces:

hello
goodbye

Going back to the example you posted, it is missing a function declaration such as:

function myFunction(a,b,func) {
  // some code goes here
}

In your post, you only posted the call to the function. Could you post the entire code, so we can better help you understand what you are seeing?


#4

There are three distinct concepts here used to great effect in JavaScript

Let’s say myfunction is the callee and the location of the call to myfunction is the caller

  1. Callback - a function passed as a parameter by the caller that can be called by the callee or by some other function known to the callee
  2. Async - function call whose complete processing does not end when callee returns - this means caller continues after callee returns but before the complete outcome of calling callee is known and processed
  3. Anonymous function - A function without a name also known as a lambda function in some languages - it can be merely convenient to use as a single-use function or something very powerful when used as a return value

These concepts are not new or unique to javascript - it’s their standard and pervasive use in javascript that make the language so special and exciting especially in the backend

In your code there is just one function call - to myfunction - the third parameter is an anonymous callback likely meant for async processing that occurs sometime later - when myfunction returns caller continues its processing

meanwhile when or as the full outcome of calling myfunction is known it is processed by the anonymous callback

the full outcome could be the handling of a UI event like a button click that cannot be predicted in advance - the caller in this case could be code to set up handlers for a calculation on a form - once the handlers are set up the caller is done - the callback could be a function that gathers various input fields and calculates a result shown on the web page after the button is clicked

it could be the response from a webserver that may take a while or timeout - the caller could be code that fires off multiple http requests to a webserver not waiting for one request to complete before firing the next - the callback could be a function that populates an HTML table with JSON data returned in the response

it could be records returned by a database query that are not available all at once - the caller could be code that prepares the query and sends it to the database server then exits - the callback could be a function that iterates over the records returned by the database using the data to update a chart in realtime


Javascript K combinator
#5

Thanks for posting the article link - It has some good explanations - on the whole it needlessly overcomplicates the concept of callbacks trying too hard to link them to functional programming - it makes questionable claims about the history and origin of callbacks - it also gets some things wrong like callbacks are not higher-order functions - rather a function that uses a callback is a higher-order function - frankly all talk of the order of functions is way too abstract and to me irrelevant to understanding the most practical aspect of callbacks which is a mechanism for existing code to provide custom processing by different users of the code


#6

I’ll admit, I trusted the top search result and didn’t read through the article.

To be honest I never understood what a higher-order function was, except that apparently methods like Array.map were higher-order. Wikipedia defines them as functions that take function(s) as arguments, and/or return a function. If that’s true then wouldn’t that make myfunction the higher-order function instead of the callback like you said?

You did a good job at a practical explanation of callbacks and the concepts related to them.


#7

Yes - myfunction is a higher-order function - it could be called a second-order function or a function of order 2 because it takes a first-order function as an argument - the idea of the order of a function comes from mathematical composition of functions and set theory

Again this has little bearing on the practical understanding and use of javascript functions - I’d stay away from these terms unless discussing the theory of programming languages


#8

You can do the same thing syntactically in Python, using lambdas, see:

https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions
http://www.secnetix.de/olli/Python/lambda_functions.hawk