0% found this document useful (0 votes)
21 views5 pages

JavaScript Callbacks Explained

Uploaded by

artursantosvale2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views5 pages

JavaScript Callbacks Explained

Uploaded by

artursantosvale2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

 Tutorials  Exercises  Services   Spaces Get Certified My W3Schools

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT

JavaScript Callbacks
❮ Previous Next ❯

"I will call back later!"

A callback is a function passed as an argument to another function

This technique allows a function to call another function

A callback function can run after another function has finished

Function Sequence
JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined.

This example will end up displaying "Goodbye":

Example

function myFirst() {
myDisplayer("Hello");
}

function mySecond() {
myDisplayer("Goodbye");
}

myFirst();
mySecond();

Try it Yourself »

This example will end up displaying "Hello":

Example

function myFirst() {
myDisplayer("Hello");
}

function mySecond() {
myDisplayer("Goodbye");
}
mySecond();
myFirst();
Tutorials  Exercises  Services   Spaces Get Certified My W3Schools

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT
Try it Yourself »

Sequence Control
Sometimes you would like to have better control over when to execute a function.

Suppose you want to do a calculation, and then display the result.

You could call a calculator function (), save the result, and then call another function () to display the
result: myCalculator myDisplayer

Example
function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}

function myCalculator(num1, num2) {


let sum = num1 + num2;
return sum;
}

let result = myCalculator(5, 5);


myDisplayer(result);

Try it Yourself »

Or, you could call a calculator function (), and let the calculator function call the display function
(): myCalculator myDisplayer

Example

function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}

function myCalculator(num1, num2) {


let sum = num1 + num2;
myDisplayer(sum);
}

myCalculator(5, 5);

Try it Yourself »

The problem with the first example above, is that you have to call two functions to display the result.

The problem with the second example, is that you cannot prevent the calculator function from displaying the result.

Now it is time to bring in a callback.


JavaScript
 Tutorials  Callbacks
Exercises  Services   Spaces Get Certified My W3Schools

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT

A callback is a function passed as an argument to another function.

Using a callback, you could call the calculator function () with a callback (), and let the calculator function run the callback
after the calculation is finished: myCalculator myCallback

Example

function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {


let sum = num1 + num2;
myCallback(sum);
}

myCalculator(5, 5, myDisplayer);

Try it Yourself »

In the example above, is a called a callback function. myDisplayer

It is passed to as an argument. myCalculator()

Note
When you pass a function as an argument, remember not to use parenthesis.

Right: myCalculator(5, 5, myDisplayer);

Wrong: myCalculator(5, 5, myDisplayer());

Example

// Create an Array
const myNumbers = [4, 1, -20, -7, 5, 9, -6];

// Call removeNeg with a callback


const posNumbers = removeNeg(myNumbers, (x) => x >= 0);

// Display Result
[Link]("demo").innerHTML = posNumbers;

// Keep only positive numbers


function removeNeg(numbers, callback) {
const myArray = [];
for (const x of numbers) {
if (callback(x)) {
[Link](x);
}
}
return myArray;
}
 Tutorials  Exercises  Services   Spaces Get Certified My W3Schools

 Try itCSS
HTML YourselfJAVASCRIPT
» SQL PYTHON JAVA PHP HOW TO [Link] C C++ C# BOOTSTRAP REACT

In the example above, is a callback function. (x) => x >= 0

It is passed to as an argument. removeNeg()

When to Use a Callback?


The examples above are not very exciting.

They are simplified to teach you the callback syntax.

Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like waiting
for a file to load).

Asynchronous functions are covered in the next chapter.

❮ Previous Next ❯

 SPACES UPGRADE AD-FREE NEWSLETTER GET CERTIFIED

CONTACT US

Top Tutorials Top References Top Examples


HTML Tutorial HTML Reference HTML Examples
CSS Tutorial CSS Reference CSS Examples
JavaScript Tutorial JavaScript Reference JavaScript Examples
How To Tutorial SQL Reference How To Examples
SQL Tutorial Python Reference SQL Examples
Python Tutorial [Link] Reference Python Examples

 [Link] Tutorial
Tutorials  Exercises 
Bootstrap Tutorial
Services  Bootstrap Reference

PHP Reference
Spaces [Link] Examples
Get Certified
Bootstrap Examples
My W3Schools
PHP Tutorial HTML Colors PHP Examples
HTML
 CSS JavaJAVASCRIPT
Tutorial SQL PYTHON Java Reference PHP
JAVA HOW TO [Link] JavaCExamples
C++ C# BOOTSTRAP REACT
C++ Tutorial Angular Reference XML Examples
jQuery Tutorial jQuery Reference jQuery Examples

Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate

    

FORUM ABOUT CLASSROOM


W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by [Link].

Common questions

Powered by AI

In the example, the callback function determines criteria for filtering. When the function removeNeg is called with the callback checking for non-negativity, it iterates through the array and applies the callback to decide which elements to keep. This functional abstraction makes the filter process adaptable by merely altering the callback for different criteria .

While simplified examples help learners grasp foundational concepts, they might not adequately prepare for real-world complexity where multiple asynchronous operations or services interact. In such cases, learners must understand how to handle variable states, error conditions, and simultaneous operations, which are often abstracted in basic tutorial examples .

Not using callbacks can lead to functions running out of sequence, particularly in event-driven programming or asynchronous tasks. Without callbacks, the program might attempt to execute functions before the necessary prerequisites are met, potentially causing errors or unexpected behavior due to incomplete data processing .

A programmer might choose to use this pattern to enhance code modularity and maintainability. By separating concerns between calculation and display logic, and using callbacks to manage execution sequencing, the code becomes more flexible and easier to modify. This is particularly effective in complex applications where multiple dependent processes need to be managed dynamically .

It is crucial because passing a function with parentheses results in executing the function and passing its return value, rather than the function itself. This would defeat the purpose of using callbacks, which is to delay execution until specific events occur as determined by the main function logic .

Using callback functions addresses the issue of needing to manually control the sequence of function execution. By having the computation function accept a callback, it automatically manages the execution of the display function once the computation is complete, thus reducing manual invocation and potential timing issues .

Callbacks enhance code involving asynchronous operations by enabling a mechanism to execute a function after an asynchronous process completes, like loading data. This helps manage workflows that depend on data availability, ensuring that actions requiring the data are not attempted before it has been successfully retrieved .

Passing a function without parentheses in JavaScript ensures the function itself is passed as an argument, rather than its result. This means the passed function can be executed later as a callback, allowing for delayed execution until certain conditions are met within the host function .

Callback functions enhance modularity by decoupling tasks into discrete, manageable units that can be easily rearranged or replaced. This separation of concerns means that individual functions can be independently maintained, tested, or debugged without affecting other parts of the code, leading to more maintainable and flexible software architecture .

Callback functions in JavaScript allow for asynchronous execution, meaning that a function can be executed after another one has finished running. This is useful for improving execution flow as it enables waiting for processes like data fetching to complete before continuing with subsequent operations .

You might also like