My Development Notes


Callback functions in JavaScript


To understand callback functions let’s write some very simple functions and see the expected output first :

Example 1

const yourSentence = function (sentence) {
  return sentence.toUpperCase();
};

const firstCapital = function (sentence) {
  return sentence[0].toUpperCase() + sentence.slice(1);
};

const sentenceConverter = function (sentence, otherFn) {
  console.log(`original input : ${sentence}`);
  console.log(`function result : ${otherFn(sentence)}`);
  console.log(`Job done by : ${otherFn.name}`);
};

sentenceConverter("hello my friends", yourSentence);

Expected output of the above :

original input : hello my friends
function result : HELLO MY FRIENDS
Job done by : yourSentence

Example 2

const yourSentence = function (sentence) {
  return sentence.toUpperCase();
};

const firstCapital = function (sentence) {
  return sentence[0].toUpperCase() + sentence.slice(1);
};

const sentenceConverter = function (sentence, otherFn) {
  console.log(`original input : ${sentence}`);
  console.log(`function result : ${otherFn(sentence)}`);
  console.log(`Job done by : ${otherFn.name}`);
};

sentenceConverter("hello my friends", firstCapital);

Expected output of the above :

original input : hello my friends
function result : Hello my friends
Job done by : firstCapital

In both the examples above you can see that we have the same functions and we have only called the first and the second functions alternately to clearly understand the results in each case.

So, what we’re doing is that we’re calling the sentenceConverter function and inside that function we’re passing the callback function. Here, the callback function is actually the otherFn function in both of the above examples.

The callback function is a function passed as an argument into another function which helps split the code into interconnected and reusable parts or blocks.

They can be very shallow or very deep based on the complexity of your project.


Leave a Reply

Your email address will not be published. Required fields are marked *