Course contentsShow
← JavaScript
Lesson 1222 of 2,72328. CallbacksFree lesson

Why Callbacks Exist

Callbacks enable asynchronous operations and customizable behavior in generic functions.

Why Callbacks Exist

You'll learn why JavaScript uses callbacks as a core pattern for handling async operations and customizable behavior.

The Core Problem Callbacks Solve

Imagine you order a pizza and the restaurant says "it'll be ready in 30 minutes." You have two options:

  1. Stand at the counter waiting (blocking) — you can't do anything else
  2. Give them your phone number (callback) — they'll call you when it's ready, and you can do other things meanwhile

JavaScript is single-threaded, meaning it can only execute one piece of code at a time on the call stack. If every operation blocked (like waiting for a file to load, a timer to finish, or a network request to complete), your entire program would freeze.

Callbacks exist to solve this: they let you say "when this operation finishes, run this function" without blocking the main thread.

Two Key Purposes

1. Asynchronous Operations
You've seen setTimeout(callback, delay) — it schedules a function to run later. The callback runs after the timer completes, but JavaScript continues executing other code immediately.

2. Customizable Behavior
Generic functions like array methods don't know what you want to do with each element. By passing a callback, you customize the behavior: array.forEach(callback) lets you define what happens to each item.

The Pattern

A callback is simply a function you pass to another function, which that function will invoke at the right time — either immediately (like in forEach) or later (like in setTimeout).

Key Takeaway: Callbacks enable JavaScript to handle time-consuming operations without freezing and allow you to inject custom logic into reusable functions.