Register Login

JavaScript Callback Function

Updated Nov 29, 2022

In JavaScript, a callback function is one of the most significant parts. JavaScript has different functions that provide a host environment allowing users to schedule asynchronous actions. In other words, these involves actions that user commences first but invoke later.

There are many real-world examples to demonstrate the functioning of the callback functions. This article will discuss what callback functions are in JavaScript, how callbacks work, and how to use them.

What are callbacks in JavaScript?

Users can define a callback function as a function passed into another function as its parameter. In other words, users can define them as a function passed to another function as an argument termed a callback function.

The browser or the JavaScript engine will run the callback function after the parent function executes. Users can use this function to develop asynchronous JavaScript code.

It is easy to create a JavaScript callback function. Users pass it as a parameter into another JS function. Then they have to call the callback function right after a particular task is over or complete to create a callback function. Let us take an example of the callback function and see how it works:

Normal Function in Javascript

Code Snippet:

function demo(x) {
	let a = [];
	for (const numb of x) {
		if (numb % 2 != 0) {
			a.push(numb);
		}
	}
	return a;
}
let x = [1, 8, 5, 7, 3, 5, 4, 10, 3, 9];
console.log(demo(x));
document.write(demo(x));

Output:

Run Code Snippet

Explanation:

In the above example, we have defined a function "demo" that takes an array of numbers as inputs and returns a new array with all the odd numbers. Secondly, we define a variable "x" as an array containing odd and even numbers. Thirdly, we call the filter() function to get all the odd numbers out of the "x" array, and the desired array is the output.

Note: One crucial point to note is users should not relate the callback as a keyword because the callback is just a name of an argument that users have to pass to another function.

How to create a callback function?

Users can create a custom callback function using a callback keyword as the last parameter. Users can then invoke it by calling the callback() function after the function ends execution.

The following code example will make the concept clear:

Code Snippet:

<h1 style = "color: maroon">JavaScript</h1>
	<p><strong>Here, we create a custom	callback function in JavaScript</strong></p>
	<script type = "text/javascript" >
		function processThis(message, callback) {
			console.log("Running function first with message: " + message);
			document.write("Running function first with message: " + message);

			if (typeof callback == "function")
				callback();
		}
		
		processThis("Hey JavaScript callback function", function callbackFunction() {
			console.log("We are using callback function.");
			document.write("We are using callback function.")
		});
	</script>

Output:

Run Code Snippet

Other built-in methods allow programmers to create, use or evaluate callback functions after a given period.  

What is the need for callback functions in JavaScript?

In JavaScript, we need to use a callback() function because many JavaScript actions are asynchronous. It indicates they do not stop the function or a program from executing until the purpose they contain inside them gets completed. Instead, the JavaScript engine will run it in the background while the other code of the JS program keeps running.

A callback() function's primary intent is to run code to any action or event in response. These events can be user-defined, such as mouse hovering, clicking, or any button. When users use a callback() function, they can instruct their application like "Hey, click on any key every time you want to end the program or to run the program!."

Another example of the callback() function:

Code Snippet:

<h1 style = "color: maroon">JavaScript Callback Function</h1>
	<script type = "text/javascript" >
		// example of a Callback Function 
		function demo(a, func) {
			console.log('Hey this is JavaScript');
			document.write('Hey this is JavaScript');
			func(a);
		}
		function demo2(a) {
			console.log('Hey' + ' ' + a);
			document.write('<br>Hey' + ' ' + a);
		}
		setTimeout(demo, 3000, 'User', demo2);
	</script>

Output:

Run Code Snippet

Example of a synchronous callback function:

Code Snippet:

<h1> This is JavaScript </h1>  
<h2> This is the JavaScriptCallbackFunction.com </h2>  
<script>  
	function showData(a, amt) {  
		alert('Hello ' + a + '\n Your entered amount is ' + amt);  
	}  

	function getData(callback) {  
		var a = prompt("Welcome to the  JavaScriptCallbackFunction.com \n Enter you first name");  
		var amt = prompt("Enter a money amount...");  
		callback(a, amt);  
	}  
	getData(showData);  
</script>  

Output:

Run Code Snippet

Explanation:

Here, the above code example involves two functions getData(callback), which accepts input from the user using a prompt box, and a function showData(name, amt), displaying the entered data by a user using an alert dialog box.

Conclusion:

Generally, every JavaScript users prefer to use callback() functions in their program. We hope this article helps programmers and web developers understand what callbacks do and how to deal with them more efficiently. Callback functions are synchronous or asynchronous, and users can use any o them based on the requirements of the JS program.


×