Before understanding callbacks it is important to understand “Asynchronous, Non-Blocking Event handling” in JavaScript.
Javascript is a single-threaded language, which means, it executes the code sequentially one line after another.
Example:
function msg(){
alert("hello")
}
var name = "Surya";
msg();
var age = 30;
In above code, the line which initializes age will not execute until the msg() function completes. This is the usual “synchronous” execution of a function.
Now this synchronous and easy to understand behavior is not desirable in many scenarios. eg: Consider a web page, where you want to alert the user when he enters an invalid input. Here, we cannot predict when the user will enter the input. It is totally depend on user . We cannot just keep on waiting for the user to enter the input and keep on checking for the validity of that input. There are other fields on the web page and the user may interact with any of them in any order. Synchronous behavior is clearly not viable since it will block the execution.
That is where “Asynchronous/Non Blocking behavior” is desired.
Callbacks are mainly used to handle the asynchronous operations like fetching or inserting some data into/from the file, and many more.
Callback are a simpler concept. A callback is basically where a function accepts another function as a parameter. At some point during execution the called function will execute the function passed as a parameter, this is a callback. Quite often the callback actually happens as an asynchronous event, in which case the called function may return without having executed the callback, that may happen later. Here is a common (browser based) example :-
function txt() {
alert("Hello, World");
}
window.setTimeout(txt, 1000);
Here the function txt
is passed as a callback to the setTimeout
function. Set timeout returns immediately however 1 seconds later the function passed as a callback is executed.
Example:
function doubleResult(num1, num2, calculate) {
return calculate(num1, num2) * 4;
}
function add(num1, num2) {
return num1 + num2;
}
function multiply(num1, num2) {
return num1 * num2;
}
console.log(doubleResult(4, 2, add));
console.log(doubleResult(4, 2, multiply));
24
32
Why do we use Callbacks in JavaScript ?
In short the way you deal with asynchrony in JavaScript is through some sort of callback mechanism. At least if you don’t want to block processing. There is no built in threading system that let’s you sidestep this requirement.
You can use callbacks through events, promises or even now, the async modifier which is basically syntactic sugar for promises, but definitely can improve readability.
Many javaScript libraries use callbacks for re-usability and generalization. Code is easier to maintain, and much more concise and readable. Every time you need to transform your unnecessary repeated code pattern into more abstract/generic function, callbacks come to the rescue.
Advantages:
Here are some of the advantages of using callbacks in JavaScript:
- Asynchronous programming: Callbacks are commonly used in asynchronous programming, which allows you to perform tasks without blocking the main thread of execution. By passing a function as a callback, you can specify what should happen when an asynchronous task completes, without having to wait for it to finish.
- Code reusability: Callbacks can be used to create reusable code, by defining a function that takes a callback as an argument and can be used with different callbacks. This can help reduce code duplication and make your code more modular and maintainable.
- Higher-order functions: By using callbacks, you can create higher-order functions, which are functions that take one or more functions as arguments and/or return a function as a result. Higher-order functions can be used for a wide range of tasks, such as filtering arrays, mapping values, and reducing values.
- Event handling: Callbacks are also commonly used for event handling, by defining a function that should be called when an event occurs, such as a mouse click or a key press. This can help create interactive web applications that respond to user input.
- Customizing behavior: By using callbacks, you can customize the behavior of a function by passing a function that implements a specific behavior. This can be especially useful in situations where you need to perform a task in different ways depending on the context.
- Callback functions are functions that are passed as arguments in other functions.
- Callbacks are mainly used to handle the asynchronous operations.
- Many javaScript libraries use callbacks for re-usability and generalization.