Be the first user to complete this post
|Add to List|
Ever wonder how callbacks work? Or how you could create your own? Callbacks have been around since a very long time and even though excessive use of callbacks can cause a lot of pain and confusion, callbacks are here to stay. In fact, even code that helps you avoid using callbacks uses callbacks internally(e.g. promises). In this article, I will use simple examples and a visualizations to demonstrate how you can use callbacks so that you can create your own when needed.
- Pass functions as an argument to the other functions, just like you pass variables.
- Return functions from other functions
callbackbecause it makes it easier to understand, and because its a good convention to have. Here’s how you would use the get function. [wpgist id="3f349f1d76fcbfc4af5d" file="usage.js"] Now lets try to visualize how this works. There are few key points to understand
- In the implementation of get function, the callback is actually a reference to the anonymous function passed to it in the usage of get. Why? Because remember we said earlier that a function is just like a variable and can be passed to other functions.
- In the implementation of the get function, when you invoke the callback with response.data, you are invoking that anonymous function with an argument.
- Pure vs Impure functions
- css - align text to an image vertically
- querySelector vs getElementById
- A simple requestAnimationFrame example visually explained
- window.onload vs document.onload
- center using css