In this article we will learn the concept of callback function in JavaScript.
Callback function in JavaScript
In this article we will try to understand the concept of
callback function in JavaScript. The callback approach is one of the examples
of function oriented programming. The concept of callback is , The function
will call another function when it will finish it’s execution. The callback
function is very necessary in various scenarios. For example, we want to show
one text after loading of page or finishing of certain animation, in those scenario
we can implement callback function.
Example of simple callback
In this example we will try to implement one simple callback
function. We know that in JavaScript ,function is one type of object and we can
send function as function argument. Here is one example
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script>
function abc() {
console.log("I am callback function");
}
function xyz(callback) {
callback();
}
xyz(abc);
</script>
</body>
</html>

Call function after type checking
Before calling to callback function we can check it’s type. It is always a best practice to check the type of argument. If the
callback argument is not function type then it will show error message in
console.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script>
function abc() {
console.log("I am callback function.Type checked");
}
function xyz(callback) {
if (typeof callback === "function")
callback();
else
console.log("It's not function");
}
xyz(abc);
</script>
</body>
</html>
Here is output of above example.

Pass argument to callback function
We can argument to callback function as normal function.
Here is sample example to do that. We are passing name and surname parameter to
callback function.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script>
function print(name, surname) {
console.log("Name:- " + name + "Surname:-" + surname);
}
function collect(name, surname,callback) {
if (typeof callback === "function")
callback(name, surname);
}
collect('Sourav', 'Kayal', print);
</script>
</body>
</html>
Callback in JQuery
JQuery is JavaScript library and have huge number of callback
function in it. In this example we are printing message after button’s click
event has occur.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="backbone/Jquery.js" type="text/javascript"></script>
</head>
<body>
<script>
$(document).ready(function () {
$("#call").click(function () {
alert("Button press");
});
});
</script>
<input type="button" id="call" value="call" />
</body>
</html>

Conclusion:-
In this example we have learned the concept of callback
function in JavaScript. Hope you understood the concept. In coming article
we will learn more about JavaScript.