JavaScript Callbacks

Pass functions to other functions.

✍️ 3 exercises + code challenge in this lesson

A callback is a function passed as an argument to another function, which calls it later.

You already used callbacks: the function given to addEventListener, setTimeout and array.map() is a callback.

Callbacks are the foundation of asynchronous JavaScript, but deeply nested callbacks ("callback hell") are hard to read. Promises and async/await solve that.

Key Takeaways: JavaScript Callbacks

Mastering JavaScript Callbacks helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Callbacks Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
function calculate(a, b, operation) {
  return operation(a, b);
}

log("Sum:", calculate(6, 3, (x, y) => x + y));
log("Product:", calculate(6, 3, (x, y) => x * y));

function loadUser(id, done) {
  log("Loading user", id, "...");
  setTimeout(() => done({ id, name: "Sara" }), 1000);
}

loadUser(7, (user) => log("Loaded:", user.name));
</script>
Free sign-in required · Google login available

JavaScript Callbacks Practice Exercises

Check what you learned in “JavaScript Callbacks”.

/ 3 solved
Fill in the blank

Pass a callback that doubles each number.

const doubled = nums.map();
✓ Correct! Not quite. Try again.
Multiple choice

What is a callback?

✓ Correct! Not quite. Try again.
Code challenge

Write a function calculate(a, b, op) that returns op(a, b). Log calculate(6, 7, (x, y) => x * y).

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services