The Wayback Machine - https://web.archive.org/web/20240920014713/https://www.geeksforgeeks.org/javascript-callbacks/
Open In App

JavaScript Callbacks

Last Updated : 22 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript is designed to handle asynchronous programming which allows us to perform multiple tasks at once without blocking the main execution thread. Callbacks are fundamental in this context, as they enable you to execute specific code after an asynchronous task is completed. Here we will see what callbacks are, why they are important, and how to implement them with practical examples.

What are Callbacks?

A callback is a function that is passed as an argument to another function and is executed after the completion of that main function. In simple terms, a callback function is called at the end of a task to either deliver results or perform an action. You pass this callback function to the main function, and once the main function completes, it invokes the callback to proceed with the next steps.

Why use Callbacks?

Callbacks are used for managing the outcomes of asynchronous tasks without blocking the program’s execution. Asynchronous tasks, like network requests or database queries, take time to finish. If these tasks were synchronous, the program would halt until they were done, resulting in a sluggish user experience.

With callbacks, though, you can keep the program running while these tasks happen in the background. When the task finishes, the callback function handles the result. This ensures the program stays responsive, enhancing the user experience.

Important Points to Know About Callbacks

1. Asynchronous programming:

Callbacks are used to handle the results of asynchronous operations, which means that the operation does not block the execution of the rest of the program. Instead, the program continues to run and the callback function is executed when the operation is complete.

2. Non-blocking:

Callbacks allow for non-blocking programming, which means that the program does not stop and wait for an operation to complete before continuing to execute. This is important for improving the performance and responsiveness of applications.

3. Higher-order functions:

A higher-order function is a function that takes one or more functions as arguments, or returns a function as a result. The main Function in the examples above is a higher-order function because it takes a callback function as an argument.

4. Anonymous functions:

Anonymous functions are functions that are not named and are often used as callbacks. The function passed to setTimeout in the first code example is an anonymous function.

5. Closure:

A closure is a function that has access to variables in its outer scope, even after the outer function has returned. This allows the callback function to access variables and information from the main function, even after the main function has completed its execution.

Real-Life Examples

1. Loading images on a website

When you load a website, images can take a while to load, especially if they’re large. If images were loaded synchronously, the website would freeze and wait for each image to load before continuing. With callbacks, you can load the images asynchronously, which means that the website continues to load while the images are being loaded in the background.

2. Handling form submissions

When a user submits a form, it takes time to process the data and send it to the server. If the form submission was executed synchronously, the user would have to wait for the data to be processed and sent before the form can be submitted. With callbacks, you can handle the form submission asynchronously, which means that the user can continue to interact with the form while the data is being processed and sent in the background.

Example Code: Basic Callback Function

JavaScript
function mainFunction(callback) {
  console.log("Performing operation...");
  // Use setTimeout to simulate an asynchronous operation
  setTimeout(function() {
    callback("Operation complete");
  }, 1000);
}

// Define the callback function
function callbackFunction(result) {
  console.log("Result: " + result);
}

// Call the main function with the callback function
mainFunction(callbackFunction);

Output
Performing operation...
Result: Operation complete

Explanation:

  • We first define a mainFunction that takes a callback as an argument.
  • The mainFunction uses setTimeout to simulate an asynchronous operation. The setTimeout function takes two arguments: a callback function and a delay time in milliseconds.
  • The setTimeout function calls the callback function with the result of the operation after the specified delay time.
  • We then define a callbackFunction that logs the result of the operation.
  • Finally, we call the mainFunction with the callbackFunction as its argument.

 Example Code: Callback with Array.forEach() Method

javascript
let numbers = [1, 2, 3, 4, 5];
function mainFunction(callback) {
  console.log("Performing operation...");
  numbers.forEach(callback);
}
function callbackFunction(number) {
  console.log("Result: " + number);
}

mainFunction(callbackFunction);

Output
Performing operation...
Result: 1
Result: 2
Result: 3
Result: 4
Result: 5

Explanation:

  • We first define an array of numbers numbers.
  • We then define a mainFunction that takes a callback as an argument.
  • The mainFunction uses Array.forEach to loop through the numbers array and call the callback function for each element in the array.
  • We then define a callbackFunction that logs each number in the numbers array.
  • Finally, we call the mainFunction with the callbackFunction as its argument.
    In conclusion, callbacks are an important aspect of JavaScript programming and are used to handle the results of asynchronous operations in a non-blocking manner. With the help of these examples, you should have a better understanding of how to use callbacks in your own projects.




Similar Reads

Understanding Callbacks and Callback Hell in JavaScript
In JavaScript, a callback is a function passed to another function to execute after an asynchronous operation completes. Callback hell refers to the problematic situation where multiple nested callbacks create a "pyramid of doom," making the code difficult to read, debug, and maintain. CallbackA callback is a function passed as an argument to anoth
4 min read
How to avoid binding by using arrow functions in callbacks in ReactJS?
In React class-based components when we use event handler callbacks, it is very important to give special attention to the 'this' keyword. In these cases the context this is undefined when the callback function actually gets invoked that's why we have to bind the context of this. Now if binding all the methods of each class is very annoying. Instea
2 min read
Callbacks and Events in Node.js
In this article, we are going to learn about Callbacks and Events in Nodejs. Both Callback and Events are important concepts of Nodejs. Let's learn about Callback first. Callback Concept: A Callback is a function that is called automatically when a particular task is completed. The Callback function allows the program to run other code until a cert
6 min read
Tensorflow.js tf.callbacks.earlyStopping() Function
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. Tensorflow.js tf.callbacks.earlyStopping() is a callback function used for stopping training when training data stop improving. Syntax: tf.callbacks.earlyStopping(args);Parameters: Thi
4 min read
Callbacks vs Promises vs Async/Await
Callbacks, Promises, and Async/Await are three different approaches in JavaScript for handling asynchronous operations. Let's briefly discuss each. CallbackCallbacks are functions passed as arguments to other functions, and they are executed after the completion of a specific task. Callbacks have been a traditional way of handling asynchronous oper
5 min read
jQuery callbacks.add() Method
The jQuery callbacks.add() method is used to add a callback or a collection of callbacks to a callback list. This method returns the callback object onto which it is attached (this).Syntax: callbacks.add(callbacks)Parameters: callbacks: This parameter holds a function, or an array of functions, that are to be added to the callback list.Example 1: T
2 min read
jQuery callbacks.empty() Method
The callbacks.empty() method in jQuery is used to remove all the callbacks from a list. It returns the Callbacks object onto which it is attached. Syntax: callbacks.empty()Parameters: It does not accept any parameter. Return Value: This method returns the Callbacks object onto which it is attached. Below examples illustrate the callbacks.empty() me
3 min read
jQuery callbacks.fire() Method
The jQuery callbacks.fire() method is used to call all the callbacks with the given arguments in the list. This method returns the callbacks object onto which it is attached (this). Syntax: callbacks.fire( arguments )Parameters: arguments: This parameter defines the argument or list of arguments to pass back to the callback list.Return Value: This
2 min read
jQuery callbacks.lock() Method
The callbacks.lock() method in jQuery is used to lock a callback list in the state. Syntax: callbacks.lock()Return Value: This method returns the callback object to which it is attached. Example 1: This example first adds and fires the function, then locks the callbacks list, and then again adds and fires the function. [GFGTABS] html <!DOCTYPE H
2 min read
How to convert function call with two callbacks promise in Node.js ?
Promise: Promise is used to handle the result, if it gets the required output then it executes the code of then block, and if it gets the error then it executes the code of the catch block. A promise looks like this - function() .then(data => { // After promise is fulfilled console.log(data); }) .catch(err => { // After promise is rejected co
3 min read
JQuery callbacks.locked() Method
The callbacks.locked() method in jQuery is used to answer whether the callbacks list has been locked or not. Syntax: callbacks.locked()Return Value: This method returns a boolean value. Example 1: In this example, the callbacks have been locked so the method returns true. [GFGTABS] html <!DOCTYPE HTML> <html> <head> <script src
2 min read
jQuery callbacks.fireWith() Method
The callbacks.fireWith() method in jQuery is used to call all the callbacks which are currently in the list with the given context and parameters. Syntax: callbacks.fireWith([context][, params])Parameters: context: This parameter defines the reference to the context in which the callbacks in the list should be fired. params: This parameter is an ar
2 min read
jQuery callbacks.has() Method
The callbacks.has() method in jQuery is used to answer whether the list has any callbacks attached. If a callback is passed as an argument, then it answers whether it is on the list or not. Syntax: callbacks.has([callback])Parameters: callback: The parameter defines the callback to search for, in the list. Return Value: This method either returns t
2 min read
jQuery callbacks.fired() Method
The jQuery callbacks.fired() method is used to check if the callbacks have already been called at least once. This method returns the Boolean value. Syntax: callbacks.fired()Parameters: This method does not accept any arguments. Return Value: This method returns a Boolean value. Example 1: This example returns true because the fire() method has bee
2 min read
jQuery callbacks.disabled() Method
The jQuery callbacks.disabled() method is used to check if the callback is disabled or not. This method returns "true" or "false" depending on the callback. Syntax: callbacks.disabled()Return Value: This method returns a boolean value. Example 1: This example disables the callback and then call the callbacks.disabled() method to see the result. [GF
2 min read
JQuery callbacks.disable() method
This callbacks.disable() method in jQuery is used to disable a callback list from doing any other operation further. This method returns the Callbacks object onto which it is attached (this). Syntax: callbacks.disable()There are two examples discussed below: Example: This example disables the callback after adding and firing a function. [GFGTABS] H
3 min read
jQuery callbacks.remove() Method
The jQuery callbacks.remove() method is used to remove a single callback or a collection of callbacks from a callback list. Syntax: callbacks.remove( callbacks )Parameters: callbacks: This parameter specifies a function, or an array of functions, which are to be removed from the callback list.Return Value: This method returns the Callbacks object o
2 min read
How to use API inside callbacks using jQuery DataTables plugin ?
Datatables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpages. DataTables is a simple-to-use jQuery plug-in with many options available for developer's custom changes. The other common features are pagination, searching, sorting, and multiple column ordering. In this article, we will learn to use
3 min read
TypeScript Optional Parameters in Callbacks
In TypeScript, optional parameters in callbacks are parameters that may or may not be provided when the callback function is invoked. They are denoted by a ? after the parameter name, allowing for more flexible function calls without requiring all arguments. Syntaxtype MyCallback = (param1: string, param2?: number) => void; function processCallb
2 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. The 'type' attribute was the most important attribute of <script> tag. However, it is no
4 min read
Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you about the basics of the scripting language i.e) Ja
4 min read
JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. <script> cons
4 min read
JavaScript Course Logical Operators in JavaScript
logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped value &&:(AND) Evaluates operands and retu
3 min read
JavaScript Course What is JavaScript ?
JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScript. HTML: HTML is used to create the structure of
3 min read
JavaScript Course Operators in JavaScript
An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used for comparing values, performing arithmetic operations, etc. There are various operators
7 min read
JavaScript Course Functions in JavaScript
Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it). Function Structure: To create a function, we use function() declaration. // Anonymous function function(){ // function...body } // function with a name function displayMessage(){
4 min read
JavaScript Course Conditional Operator in JavaScript
JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the code block inside it will be executed otherwise n
3 min read
JavaScript Course Objects in JavaScript
We have learned about different Data Types that javascript provides us, most of them primitive in nature. Objects are not primitive in nature and are a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to st
4 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
Article Tags :