Avatar of Bruce Gust
Bruce Gust
Flag for United States of America asked on

How does "callback" work in JavaScript?

Here's my code:

function doHomework(subject, callback) {
  alert(`Starting my ${subject} homework.`);

doHomework('math', function() {
  alert('Finished my homework');

Open in new window

If I run this, I'll get two alerts. The first one says, "Starting my math homework" followed by "Finished my homework."

From what I understand, "callback" is a function that ensures whatever functionality its attached to, that code won't run until AFTER the other code has fired. But I don't understand how that works in this scenario.

If I remove the callback function and make my first block of code look like this:

function doHomework(subject) {
  alert(`Starting my ${subject} homework.);

Open in new window

I'l get one alert saying, "Starting my math homework." But "Finished my homework" doesn't show up at all.

Why? What happened? Why didn't "Finished..." show up and how does "callback" make things work the way you would expect them to?

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon

View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Bruce Gust

Kimputer (love that handle)!

I just got done reading another article that makes your explanation all the more relevant.

I'm going to explain this back to you and you tell me if I've got it.

A callback function is a function called within another function. In the example I used, the "callback" variable is actually the function that triggers the "Finished my homework" alert. Without that variable being passed into the "doHomework" function, it would never be triggered.

I was looking at this initially purely from the standpoint of the order that the functions were being fired. If the above explanation is right, I think I've got it.

Julian Hansen

A callback function is a function called within another function
Yes but that is not the definition - any function can be called inside a function.

A callback is a function passed as a PARAMETER to another function so that the called function can invoke it at some point - usually when the called function has finished doing what it is supposed to do.

Callbacks are usually used for ASYNC functions - where you have an indeterminate amount of time before a called function completes and you want to keep processing other code while waiting for it to complete.

You pass a callback to the ASYNC function with the code you want to run when the ASYNC operation completes.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck