Skip to content

Latest commit

 

History

History
99 lines (68 loc) · 2.39 KB

File metadata and controls

99 lines (68 loc) · 2.39 KB

Callback Functions in JS & Event Listeners

What is a Callback Function?

Definition: A callback function is a function that is passed as an argument to another function and is invoked later, either synchronously or asynchronously.

Think of it as: "I'll call you back when I'm ready."

Example:

function greetUser(name, callback) {
  console.log(`Hello, ${name}`);
  callback();
}

function sayBye() {
  console.log('Goodbye!');
}

greetUser('JavaScript', sayBye);

Output:

Hello, JavaScript
Goodbye!

Why Callbacks Are Useful

  • They allow functions to be reused with different behaviors.
  • They handle asynchronous operations (before Promises & async/await became common).
  • They help execute code only after something else finishes (e.g., data fetch, timer).

Callbacks in Asynchronous JS

Example with setTimeout:

setTimeout(function () {
  console.log('3 seconds passed!');
}, 3000);

The function is passed as a callback and executed later by the event loop.

Event Listeners as Callbacks

Event listeners always require a callback function that runs when the event happens.

Example:

document.getElementById('btn').addEventListener('click', function () {
  console.log('Button clicked!');
});

Here, the anonymous function is the callback. The browser calls it only when the user clicks the button.

Named Callback for Reusability

function handleClick() {
  console.log('Button clicked!');
}

document.getElementById('btn').addEventListener('click', handleClick);

Cleaner, reusable, and easier to remove later:

document.getElementById('btn').removeEventListener('click', handleClick);

Callback Hell (Nested Callbacks Problem)

Too many callbacks can cause deeply nested, hard-to-read code:

doStep1(function (result1) {
  doStep2(result1, function (result2) {
    doStep3(result2, function (result3) {
      console.log('Done!');
    });
  });
});

This led to Promises and async/await in modern JS.

Interview Soundbite

"A callback function is a function passed as an argument to another function, to be executed later. They're heavily used in JavaScript for async operations like timers, network requests, and event handling. Event listeners are a common real-world example of callbacks — you register a function, and the browser 'calls it back' when the event happens."