Callback Functions

It has been about three weeks since the start of my time at Flatiron's coding boot camp and in that time I have learned various skills which have been at times very difficult to understand. One of those skills happens to be the use of callback functions and although my understanding of the subject is still growing I'd like to share what I have learned thus far.

What are callback functions? Callback functions are a method used to take a former function and invoke it within a later function. A callback's purpose is to execute code in response to an event.

We have to also understand what a synchronous and asynchronous function is which will determine how the functions will execute. Synchronous callbacks are executed at the same time as a higher-order function that uses a callback function. Asynchronous callbacks allow us to run other tasks before previous tasks have been completed making potentially long tasks shorter. In short synchronous callbacks run in an order and asynchronous can run functions together and execute them when they are needed.

Synchronous:

Task A ---> Task B ---> Task C ---> End Result

Asynchronous:

Task A -------->

Task B --------> End Result

Task C -------->

As detailed, a synchronous function will run one at a time and will not move on until the previous ones were completed. On the other hand, asynchronous allows us to run all of the functions together and will be completed simultaneously. This will be

Example of a Callback Function: In this case, myDisplayer is the callback function

function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}

function myCalculator(x, y, myCallback) {
let sum = x + y;
myCallback(sum);
}

}

myCalculator( a, b myDisplayer )

The callback function is being used within our second function as an argument letting us keep the function outside and use it as needed. The asynchronous capabilities allow long codes to run more efficiently.

There can be drawbacks to these callback functions as well when they become too nested. When calling these functions within a function it is easy to lose track of all the elements making it less readable. It is important to keep track of all the functions being used and remember to have too much nesting.

In conclusion, callback functions are a great technique for asynchronous execution and if used correctly will be a great way to create efficient code. I am continuing to learn about callback functions and all of their utilities, which is frustrating but at the same time it's exhilarating to learn. So here's to more learning ahead.

Any comments are welcome to help me understand anything better.