Callback Functions JavaScript

mmweerarathna
2 min readNov 6, 2023

--

A callback function is passed into another function as an argument, and the function can call back the passed function at any given time. The following example shows how to create and use a callback function.

//Declared Functions
function functionOne() {
console.log('functionOne');
}

function functionTwo() {
console.log('functionTwo');
}

function functionThree() {
console.log('functionThree');
}

//Scenario One
functionOne();

//Scenario Two
functionOne();
functionTwo();

//Scenario One Output
//functionOne

//Scenario Two Output
//functionOne
//functionTwo

There are three functions named functionOne, functionTwo, and functionThree in the above example, and all of these functions contain a console.log() line that prints out the function of the name into the console. Now in scenario One (mentioned in the code with a comment), we call the functionOne, and it prints out the name of the function to the console as defined, but we need to call the functionTwo after executing the functionOne and scenario Two exactly shows how we can implement that requirement. There is another scenario in which we need to consider understanding this callback function correctly. Imagine that after executing functionOne we need to execute functionThree and another time we need to execute functionTwo depending on the operation on functionOne, and we can do that easily with the use of callback functions, as explained in scenario Three.

//Scenario Three
//Functions are redeclared by changing
//them for the third scenario

function functionOne(cbFunction) {
console.log('functionOne');
cbFunction();
console.log('line after call back function');
}

function functionTwo() {
console.log('functionTwo');
}

function functionThree() {
console.log('functionThree');
}

functionOne(functionTwo);

//Output
//functionOne
//functionTwo
//line after call back function

In scenario three, we call the functionOne and we pass functionTwo to the functionOne as an argument. Now, what happens inside the functionOne is that it prints the console.log() line first, and then after that, it executes the callback function that’s passed as a parameter to function functionOne and then after that, it prints the next console.log() line in functionOne().

--

--