Explanation of Callback function in JavaScript
Hello everyone, in this article we are going to talk about callback function in JavaScript. We will demonstrate callback and we are going to make examples on Callback.Let's begin
What is callback function ?
A callback function is that a function which can be passed as parameter to another function.
function printStrings(name, surname) {
var fullName = name + " " + surname;
alert(fullName);
}
printStrings("Burak Hamdi", "TUFAN");
//output will be Burak Hamdi TUFAN
As you can see above we passed some parameters inside a function and we used them.
Now let's make an example with callback functions. As I mentioned above we are going to send a function as an argument to another function.
// declare a normal JavaScript function
function printStrings(name, surname,callbackFunction) {
var fullName = name + " " + surname;
console.log(fullName);
callbackFunction();
}
// declare callback function
function printWeb() {
console.log("This message from callback function.");
console.log("thecodeprogram.com");
}
// send callback function as argument into normal function
printStrings("Burak Hamdi", "TUFAN", printWeb);
Example Output
Burak Hamdi TUFAN
This message from callback function
thecodeprogram.com
As you can see above our function is called the callback function which sent as argument
So, When the callback functions are good options?
As I mentioned before we are sending the function as argument. So we can execute a function after specified task is performed. They are good to make the design easier. When we use the asynchronous methods we may need to call some external functions after specified task is executed. One of best usages are Ajax Requests. We can call execute some functions after server request is incame.
setTimeout(function, milliseconds, [arg1], [arg2], [...]);
function printStrings(name, surname,callbackFunction) {
var fullName = name + " " + surname;
console.log(fullName);
callbackFunction();
}
function printWeb() {
console.log("This message from callback function.");
console.log("thecodeprogram.com");
}
setTimeout(printStrings, 5000, "Burak Hamdi", "TUFAN", printWeb);
printStrings("TheCode", "Program", printWeb);
Program output will be
TheCode Program
thecodeprogram.com
Burak Hamdi TUFAN
thecodeprogram.com
As you can see above program will call the setTimeout and printStrings functions synchronicity. In setTimeout function, execution will begin after 5 seconds and independently. If we wait for some external data from server, callback methods are good to use to process some incoming data from server.
That is all in this article.
Burak Hamdi TUFAN
Comments