Callback functions
This article will revolve around the below questions:
- What is a callback function?
- Syntax of the callback function
- When to use a callback function?
- Best practices
What is a Callback function?
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. Implementing callback is also called the callback pattern.
Syntax
- function outerFunction(callbackFunction) {
- //Some code here
- callbackFunction();
- }
- function callbackFunction(){
- //some code here
- }
When to use a callback function?
1. Synchronous callback functions
These functions are used to make the code more versatile.
For example, you can perform different operations on data after getting the input from the user.
- function getNumbersFromUser(callbackFunction){
- //some code here
- //Numbers a,b received from a user
- var a = 4, b = 5;
- callbackFunction(a,b);
- }
- function multiplication(a,b){
- document.write("Multiplication is : "+a*b);
- }
- //Can perform multiple operations on the same number set.
- getNumbersFromUser(multiplication);
- //OR
- function addition(a,b){
- document.write("Addition is : "+(a+b));
- }
- //Can perform addition operations on the same number set by just changing callback function.
- getNumbersFromUser(addition);
The above series of operations can be performed without a callback function in the following ways.
- //Call function within another function
- function getNumbersFromUser(){
- //some code here
- //Numbers a,b received from a user
- var a = 4, b = 5;
- multiplication(a,b);
- }
- function multiplication(a,b){
- document.write("Multiplication is : "+a*b);
- }
- getNumbersFromUser();
- //------------OR-----------------
- function getNumbersFromUser(){
- //some code here
- //Numbers a,b received from a user
- var a = 4, b = 5;
- addition(a,b);
- }
- function addition(a,b){
- document.write("Addition is : "+(a+b));
- }
- getNumbersFromUser();

Elavarasan RPosted Sep 24, 2019, 10:00 PM
Great. nice article..