What is a callback and how is it used?

👨‍💻 Frontend Developer 🟡 Often Asked 🎚️ Easy
#JavaScript #Functions #JS Basics

Brief Answer

callback is a function that is passed as an argument to another function and is called inside it at a certain moment. Callback allows one function to “call” another function when some operation is completed.

// Regular function
function greet(name) {
  console.log('Hello, ' + name);
}
 
// Function accepting callback
function processUser(name, callback) {
  // Do something with name
  const processedName = name.toUpperCase();
  // Call callback
  callback(processedName);
}
 
// Usage
processUser('john', greet); // 'Hello, JOHN'

Full Answer

A callback is like asking someone to pass a message to another person. You give your friend a note (function) and say: “When you meet Peter, give him this!”. The callback is that note! 📝

What is a Callback

A callback is a function that you pass to another function so that it calls it at the right moment. This allows functions to work together and coordinate their actions.

Simple Examples

Basic Callback Example

// Callback function
function showMessage(message) {
  console.log('Message: ' + message);
}
 
// Function using callback
function doSomething(action, callback) {
  console.log('Doing ' + action);
  callback('Done!');
}
 
// Usage
doSomething('work', showMessage);
// 'Doing work'
// 'Message: Done!'

Callback with Parameters

function calculate(a, b, operation, callback) {
  const result = operation(a, b);
  callback(result);
}
 
function showResult(result) {
  console.log('Result: ' + result);
}
 
// Usage
calculate(5, 3, (x, y) => x + y, showResult); // 'Result: 8'
calculate(5, 3, (x, y) => x * y, showResult); // 'Result: 15'

How Callbacks Are Used

In Asynchronous Operations

// Simulating data loading
function loadData(callback) {
  console.log('Starting loading...');
  
  // Simulating delay
  setTimeout(() => {
    const data = 'Data loaded';
    callback(data);
  }, 1000);
}
 
// Usage
loadData(function(result) {
  console.log('Success: ' + result);
});

In Event Handlers

// Simulating click handler
function onClick(callback) {
  console.log('Waiting for click...');
  // When click happens
  callback('Click performed!');
}
 
// Usage
onClick(function(message) {
  console.log('Event: ' + message);
});

When to Use Callbacks

For Processing Results

function validateEmail(email, successCallback, errorCallback) {
  if (email.includes('@')) {
    successCallback('Email is valid');
  } else {
    errorCallback('Email is invalid');
  }
}
 
validateEmail(
  'test@example.com',
  (msg) => console.log('Success: ' + msg),
  (msg) => console.log('Error: ' + msg)
);

For Code Flexibility

function processArray(arr, callback) {
  const result = [];
  for (let item of arr) {
    result.push(callback(item));
  }
  return result;
}
 
const numbers = [1, 2, 3];
const doubled = processArray(numbers, x => x * 2);
console.log(doubled); // [2, 4, 6]

Common Mistakes

Passing Result Instead of Function

function doWork(callback) {
  const result = 'work done';
  // ❌ Error — calling function instead of passing
  // callback(result); // if callback is not a function, will be error
  
  // ✅ Correctly — check that callback is a function
  if (typeof callback === 'function') {
    callback(result);
  }
}

Forgetting to Call Callback

function asyncOperation(callback) {
  // ❌ Error — forgot to call callback
  // return 'result';
  
  // ✅ Correctly — call callback
  callback('result');
}

Simple Rules

  1. Callback — function passed as argument to another function 📨
  2. Call — callback is called inside receiving function 📞
  3. Asynchrony — often used for asynchronous operations ⏱️
  4. Flexibility — allows customizing function behavior 🔧
  5. Check — always check that callback is a function ✅

Callback is a simple but powerful concept that underlies many JavaScript patterns. Modern JavaScript is inconceivable without them! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪