Callback

A function passed as an argument to another function, which is then executed at a later time or after a specific event occurs.

Overview

Callbacks are a fundamental concept in JavaScript, enabling asynchronous programming and event handling. They allow you to specify what should happen after an operation completes, without blocking the execution of other code. Callbacks are commonly used with array methods, event listeners, and asynchronous operations.

Example

javascript
// Array method callback
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
  return num * 2;
});

// Async callback
setTimeout(function() {
  console.log('Executed after 1 second');
}, 1000);

// Event listener callback
button.addEventListener('click', function() {
  console.log('Button clicked!');
});

// Custom function with callback
function fetchData(callback) {
  // ... fetch data
  callback(data);
}

Key Points

  • Function passed as an argument
  • Executed at a later time
  • Enable asynchronous programming
  • Can lead to "callback hell" when nested deeply
  • Modern alternatives: Promises and async/await

Learn More