troubleshooting Question

How does "callback" work in JavaScript?

Avatar of Bruce Gust
Bruce GustFlag for United States of America asked on
JavaScript
3 Comments1 Solution102 ViewsLast Modified:
Here's my code:

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

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

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.);
}

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?
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 3 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros