0
0
Javascriptprogramming~5 mins

Callback pitfalls in Javascript

Choose your learning style9 modes available
Introduction

Callbacks let us run code after something finishes. But if not careful, they can cause confusion or errors.

When you want to do something after a file loads.
When you need to wait for a timer before running code.
When you want to handle user clicks and then update the page.
When you want to get data from a server and then show it.
When you want to run several tasks one after another.
Syntax
Javascript
function doSomething(callback) {
  // do work
  callback();
}

doSomething(() => {
  // code to run after work
});

Callbacks are functions passed as arguments to run later.

They help with tasks that take time, like loading data.

Examples
This runs the greeting, then runs the callback to say it's done.
Javascript
function greet(name, callback) {
  console.log('Hello ' + name);
  callback();
}

greet('Alice', () => {
  console.log('Done greeting');
});
Runs the code after 1 second delay using a callback.
Javascript
setTimeout(() => {
  console.log('Waited 1 second');
}, 1000);
Callback receives data after loading finishes.
Javascript
function loadData(callback) {
  // simulate data loading
  setTimeout(() => {
    callback('Data loaded');
  }, 500);
}

loadData(message => {
  console.log(message);
});
Sample Program

This simulates fetching user data. If userId is 0, it returns an error via callback. Otherwise, it returns user info. It shows how callbacks handle success and error.

Javascript
function fetchUserData(userId, callback) {
  setTimeout(() => {
    if (userId === 0) {
      callback('Error: User not found', null);
    } else {
      callback(null, { id: userId, name: 'User' + userId });
    }
  }, 1000);
}

fetchUserData(0, (error, data) => {
  if (error) {
    console.log(error);
  } else {
    console.log('User data:', data);
  }
});

fetchUserData(1, (error, data) => {
  if (error) {
    console.log(error);
  } else {
    console.log('User data:', data);
  }
});
OutputSuccess
Important Notes

Callbacks can cause "callback hell" if nested too deep, making code hard to read.

Always handle errors inside callbacks to avoid silent failures.

Use named functions for callbacks to keep code clearer.

Summary

Callbacks run code after a task finishes.

They can cause confusion if nested or errors are not handled.

Write clear callbacks and handle errors to avoid problems.