Holla back with Callback functions
Like most developers, I had a rocky start with learning Javascript. It was a bit tricky to wrap my head around some of the concepts, flows and logical. I thought I would never get it, but I did and one of the things that helped me solidify my understanding of JS, was callback functions( say what?!?!)
It just kinda made sense to me and once the stone was rolling, it was all down hill from there.
So what is a callback function? ( fun fact : it is also know as a higher order function)
A callback function is function that is passed to another as a parameter, then the call back function is called and executed inside the other function.
The function itself does not execute until the original function that is using it as a parameter is called. Hence the name… callback
There is some confusion about how callback functions are used.
So
Lets break it down.
function acknowledgment (name){
alert( ‘Hey ’ + name); }
function userName(callback){
let name = prompt(‘Whats your name ?’);
callback(name);
}
userName(acknowledgment);
As you can see in the example above, when our acknowledgment function it is called with userName function it is used a parameter to displays the alert.
In short callback functions are used to indicate that something will happen (an event) inside of another function.
Don’t forget that callback functions are still that functions, so they can be passed parameters
So why holla back to other functions ?
Because JS is an event driven language, that usually is waiting a response from something before being able to move on.
Using these nifty functions can make your code DRY, as well as easier maintain making better for you read and having specialized functions.
Callback functions are super cool functions that can have great benefits to your websites and applications. Try to implement them into your code as you move forward when the occasion calls for it !