Javascript Callback Function in Simple Manner
In this article you will see some simple example to understand how callback function works.
let argument = 101;
Here we have a variable called argument which is storing 101.
function display(parameter){
console.log(parameter);
}
And here we have a display function which have one parameter called parameter. After we pass any argument in display function this will be first stored in parameter and then show it to the console.log. Let’s pass the argument variable in display function
let argument = 101;
function display(parameter){
console.log(parameter)
}
display(argument)
//output: 101
Suppose now we want to pass a function to display function and want to call it inside display function. How would we do that?
First let’s define a function called addTwoNumbers
function addTwoNumbers(){
console.log('This function will add two number');
}
and also we have display function
function addTwoNumbers(){
console.log('This function will add two number');
}
function display (print){
print();
}
Clearly we can see that display function has a parameter called print which is expecting a function and inside display function we are calling that function which we will get as a argument sent to this display function.
Let’s call the display function with an argument which will be our addTwoNumbers function.
function addTwoNumbers(){
console.log('This function will add two number');
}
function display (print){
print();
}
display(addTwoNumbers);
//output: This function will add two number
Now you have learned the callback function. When we pass a function to another function that function which is passed as an argument is called callback function.
As we know we can pass arguments to a function when we are calling it.
function addTwoNumbers(num1, num2){
console.log(`First number is ${num1} and second number is ${num2}`);
}
function display (print){
print();
}
display(addTwoNumbers);
//output: First number is undefined and second number is undefined
Now our addTwoNumbers function are taking two parameter called num1, num2. Let’s call it with arguments inside display function
function addTwoNumbers(num1, num2){
console.log(`First number is ${num1} and second number is ${num2}`);
}
function display(print){
print(101, 201);
}
display(addTwoNumbers);
//output: First number is 101 and second number is 201
We know that a function will return something. We can now return the addition value from the addTwoNumbers.
function addTwoNumbers(num1, num2){
return num1+num2;
}
function display(print){
print(50, 60);
}
display(addTwoNumbers);
//output:
Nothing happens because we have to store the return value. Then we can console log it.
function addTwoNumbers(num1, num2){
return num1+num2;
}
function display(print){
let sum= print(50, 60);
console.log(`Sum is ${sum}`);
}
display(addTwoNumbers)
//output: Sum is 110
That’s how we can use a callback function as a parameter inside another function.