The most common Node.js backend interview mistake – answered by the Concise Software!
I’m gonna call you back later on
Callbacks are just regular functions but they are in use in a not very common way. In a classic approach we declare and define a function to use it later. About callbacks there is the same function creation process but these functions are also passed as parameters to other functions. This approach gives us the possibility to dynamically call function from function. Can you see a huge potential here? We can change the implementation of some general function by passing different parameters to the function next calls and that is not all! Callbacks can be automatically called after another function execution is finished. Below we have an example of a callback function.
We can see here myCallback() function which is passed as a parameter for the setTimeout(). After three seconds our callback function will be fired and in the console we will be able to see “My Callback function has been fired!” logged string.
This feature provides a lot of opportunities to write awesome code. Let’s consider an example. Below we can see the multiplier() function which accepts the first number to make multiplication. Multiplier returns a second function which accepts a second factor for our mathematical operation. At the end we can call multiplier() twice to pass two multiplication’s factors.
Can callback be closure?
The most common Node.js backend interview mistake – summary
Let’s summarize knowledge from the whole entry. First of all, callbacks are functions which are passed into other ones as arguments and can be fired after the parent’s execution is finished. We can use them to handle asynchronous calls, but nowadays a more convenient way to handle asynchronous calls is to use promises.
On the other hand we have closures, which are elements bonded into master function and have access to the context environment of their parent. Mentioned before callbacks can be called as closures if they depend on the parent’s context.
Are you ready to work on amazing projects?
This may interest you:
5 reasons to build your backend using Node.js
Node.js vs Python: Which one to choose for your project?
From underground to enterprise – story of the Node.JS
6 examples of enterprise Node.js projects