Callbacks in Node.js: a different explanation

Node is great for many things, but it is mostly know because it uses JavaScript as programming language and it has that amazing feature called asynchronicity using callback.

Now, there are many articles and videos explaining callbacks, most of them great. But it takes a great deal to understand them. I believe this is because they are written by programmers for programmers… and that makes sense. But what if you are a programmer and still are not getting it?

Okay, so, let me give it a try:

The key thing is that you need to understand that there is nothing really new here. Well, there maybe is, but it is easy to understand: a function can be passed to another function as a parameter.
What does that mean? Imagine a simple javascript function. That function has some code and when your program is run, the code of the function sits somewhere in the computer’s memory. Right? Well, say that the function code when it is on memory is 1000. You don’t know where that is and it will change every time you run the program. S, how do you call it? You already know that, you call it by a name. When you declare function hello(), it is placing your code in memory (let’s say this time is position 1000) and that memory address is stored in a variable called ‘hello’, so that everytiem you call ‘hello’ it will go seek some code at the memory position 1000 and process it.
We good? Okay, let’s keep going.

We said that ‘hello()’ is just a pointer to a location in memory with some code. Same as if intestad of a piece of code it is a piece of data. Let say you declare a variable like ‘var a = 2;’. It is doing the same: putting somewhere in the memory the value “2”, and assiging to the name “a” the memory location where the value is. So when you need to retrieve it again, you just need to call ‘a’

The only difference is that when you declare a function, you are telling the machine (preprocessor, compiler or whatever it it) that it is going to find a piece of code (a function) or a piece of data.

So let’s say we have
1000: hello()
1050: 2
1010: goodbye ()

The same way you pass a variable, you can pass a function because it is just a location in the memory. Therefore you can do things like hello(a, goodbye), passing a variable and a function.

Hope this was useful!

Nelson Muskus

Published by

Nelson Muskus

Full Stack developer

Leave a Reply

Your email address will not be published.