What is a call back function?

What is a call-back function?

Think house hold chores. Well a call back is basically a chore which needs to be done exactly after another chore is done. It’s basically two chores that are stuck together. (If you really really want to get technical then the second chore need not be executed after the first, but for the moment let’s just assume that the second is executed after the first).

Example Consider this scenario:

• Chore 1: put the dishes away. • Chore 2: wash the dishes.

Question: Which chore should come first? And which chore is the “call-back function”?

Answer: Well, ideally you’d want to put the dishes away after washing them. Hence Chore 1 would be the call back function. (yeah, I tricked you with the number ;) )

But wait there’s more… A call-back function is: “passed as an argument into another function”. What the heck does that mean? It basically means that you must specify the chore that needs to be done at the end when you demand the first chore is done.

Example: Wife: I want you to (i) cook dinner tonight and then (ii) wash the dishes. (It’s a tough life). Because washing the dishes is meant to be done after cooking dinner then in code it should look something like this:

CookDinner( washDishes);

And when I get to the end of cooking dinner (CookDinner) I’d simply wash the dishes. In other words I would be “invoking” the washDishes method.

Please note that washDishes is an “argument” that is not your typical argument. Underneath the covers it is actually a method. But it’s disguised as an object. These objects are called: delegates. (If you don’t know what an argument is, think of it as something (i.e. a number, a string etc.) which is passed into a function.

Written on November 29, 2016