— Callbacks in Javascript —

Mariam Antar
Sep 1, 2018 · 3 min read

Because functions are first class objects they can be passed as arguments in another function and later execute that passed function or return it to be executed later. It is a function provided as a parameter to other methods such as ‘for each’ and is invoked as a certain point in time.

// here we are declaring the callback function inside the code
var fruit = ["apple", "banana", "pear" ];
// now we want to loop through the array and pass a callback function
// for each cycles through each fruit and with that we pass a callback function which can do something with the data given which in this case passed a value from the array
fruit.forEach(function(hello) {
console.log(hello)
});

Why do we need callbacks?

A callback is a way of requesting a task in advance because you don’t know when it is going to be done but when it happens you want the code to execute.The code below is a good way to execute the result but what we want it to be more functional in terms of how it gets executed.

// we have created a function called calc whcih takes 3 arguments, one which determines the calcualtion type
let calc = function(num1,num2, calcType){
// inside the function we have created an if statement to make a decision
if(calcType === 'add')
return num1 + num2;
else(calcType === 'multiply')
return num1 * num2;
};
// here we have given our function three arguments with the calctype of add which will add both numbers together when the code executesconsole.log(calc(5,6,'add'));

Here is a good example of a functional way to execute the code using a callback function. We have defined two callback functions and and then executed the callback function inside the calc function. To call it we pass two arguments (since we are adding) with the function we want to call.

// takes two arguments
let add = function(a,b){
return a + b
};
let multiply = function(a,b){
return a * b
};
let calc = function(num1,num2, callback){
// we execute the callback function here
return callback(num1,num2);
};
// here instead of passing the string add like the previous code, we pass the add functionconsole.log(calc(7,6,add));

Callbacks can be synchronous or asynchronous. A synchronous callback happens immediately before a function returns, executed by a blocking method. It waits til the operation is complete before moving onto the next statement. Carefully read the code below as an example.

// this is a synchronus callback, it happens immediately before the function returns
// here is another way to invoke a callback function
function callback(val){
console.log(val);
}
// here we are declaring the callback function inside
var fruit = ["apple", "banana", "pear" ];
// now we want to loop through the array and pass a callback function
// for each cycles through each fruit and with that we pass a callback parameter to grab the data
fruit.forEach(callback); {
// after it calls everything at once this will get called
console.log("all done")
};

An asynchronous callbacks which are used more happen after a function returns. They are set to be executed after an asynchronous procedure finishes or when a specific event occurs (page load, click, AJAX response arrival, and so on). Below is a simple example of an asynchronous function which demonstrates it where we invoke setTimeout() with the doLater() function as a callback parameter and, after 1000 milliseconds of waiting, the doLater() callback is invoked:

var alertMessage = 'One second passed!'; function doLater() {alert(alertMessage);}setTimeout(doLater, 1000);

Callback hell occurs when we’ve got one callback running after another which is a problem because your nesting function after function and the code begins the get hard to read.Promises are used to fix this.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade