Marcus Node Bits - Callback function is cool stuff, and I even know how to write them

· February 6, 2014

I’m writing down some of the things I’ve picked up when I started to learn about Node, Express, and Mongo. Here are all the posts in the series:

This is not Node related but rather a Javascript thing that was something that I had a real hard time with at first. And I know that I should learn about promises, but I haven’t yet.

Functions are first class citizens in Javascript, which is super cool and something that you’ll make use of A LOT. Passing functions to functions is just the way to go in Node code. One thing that this manifests itself is through the concept of “callbacks”.

Callbacks are pretty easy on the concept level; a function does something and then “call back” to the caller when the work is done. The callback is simply a function that you pass to the function as a parameter. Like this function:

function doSomething(p, callback) {
    // .. do stuff

Quite simply (eh … not really the first time I saw this but anyway) doSomething will execute using 123 as the p parameter. It will finally call the callback function and hence execute my little anonymous function that does the console.log.

It took some time to wrap my head around this. And Yes, I know that promises are the new kid on the block, but I haven’t come there yet.

The first time it really clicked for me was actually when I started to write my code in another way. It was since I messed up the parentheses, curlys, and semicolons a lot. So I write (most often) my function calls in this sequence, which helped me realize that the function is just another parameter. It also saved me from a lot of JSLint errors.

After a while, this way of writing will get boring and tedious so I will stop. Right now it helps me understand the structure so I’ll keep doing this.

Just to be clear, I love JSLint and it makes me look like I know how to write proper, well-formatted Javascript, when I actually don’t :) There’s an excellent plugin to Sublime. Get it now.

Twitter, Facebook