Callbacks: Scary words in programming, episode 5

Welcome to episode 5 of Scary Words in Programming, part of the carnival!

scary-words-in-programming-with-pam

Callbacks

I’m pulling again from the suggestions I got on Twitter, and I can see how callbacks are scary & confusing at first! Callbacks are to put it very very simply, using a function as an argument to another function. That looks something like this.

function add(x, y) {
  return x + y;
}

// Say this in your head: "the function handler takes arguments a & b and returns p of a & b"
function handler(a, b, p) {
  return p(a, b);
}
handler(2, 3, add); // returns 5, or 2 + 3

If that’s all “oh, whatever, cool, I got it, carry on,” you need to remember when you were first learning JavaScript and had to wrap your head around the fact that no one writes their callbacks like that, the write them like:

function handler(2, 3, function(x, y) {
  return x + y;
});

With a tasty, tasty, anonymous function callback, the befuddlement of every JS101 students I’ve had, ever.

Which, as a tangent, leads to one of my favorite stranges in JavaScript, of what’s an “anonymous” function. Kyle Simpson hates them, but face it, they’re everywhere. Pop quiz. Is this an anonymous function?

var myFunction = function() {
  return 'foo';
}

It actually is: it’s a function expression assigned to a variable. Essentially, if you see the word function touching its parentheses (function()) it means it didn’t get assigned a name, and is an anonymous function. Naming your functions will make that callback better in a trace, and maybe easier to read (untested on JS101 students):

function handler(2, 3, function add(x, y) {
  return x + y;
});

I don’t know if Kyle’s crusade will catch on (hopefully it does), but I know the anonymous function as idiom will be hard to die out.

This post is part of the Scary Words in Programming Carnival! Check out other posts, and feel free to join in!

Tags: , ,

No comments yet.

Leave a Reply