# Callback Functions

A function that takes another function as one of its parameters is termed as callback function. This is an interesting concept but developers generally tend to ignore it. Many languages support this feature – some do it easily while others need some code setup. In this post, I will be using Javascript to demonstrate a simple callback function implementation. JQuery is an example library that used callback functions extensively.
How it works
Lets get into an imaginary world for a minute. This will be followed by a simple code example.
Assume that function A (fnA) calls function B (fnB) by passing some parameters. fnB performs a set of actions. Imagine a case where fnB is supplied by a third party and it is not easy to change its behavior.
Now, there is a specific part of fnB that has to be executed differently. We can achieve this by designing fnB as a callback function.
In addition to normal parameters, fnB also takes a new function (say fnC) as another paramter. fnA now calls fnB with normal parameters AND a new function pointer to fnC. fnB will then execute fnC at a designated point.
Advantage of this approach is that fnA can now manipulate the behaviour of fnB by not modifying fnB source code but by changing what goes into fnC.
Example Scenario 1
Lets take the normal case. Create functions to calculate areas of square and circle. Call these from a parent function (like window.onload).

```function areaSquare(side) {
var length = side;
var area = 0;
if (length < 0) {
return false;
}

area = length * length;
}

function areaCircle(side) {
var area = 0;
return false;
}
}

areaCircle(10);
areaSquare(9);
};
```

Two key observations can be made on the above code:
1. There is some common logic between the 2 functions that can be generalized
2. New functions have to be written if the users want to calculate areas for polygon or hexagon or use their own formula.

Example Scenario 2 – Callback function
The above code can be improved by using callback functions and solving the 2 key observations made.

```function areaCalculatorCallback(inputData, inputFunction) {
var input = inputData;
var area = 0;

if (input < 0) {
return false;
}
area = inputFunction(input);
}