0
0
Javascriptprogramming~5 mins

Callbacks in Javascript

Choose your learning style9 modes available
Introduction

Callbacks let you run a function after another function finishes. This helps when you want to wait for something to happen before moving on.

When you want to do something after a button is clicked.
When you need to wait for data to load from the internet before showing it.
When you want to run a task after a timer ends.
When you want to handle a response after a file is read.
When you want to run code after a user finishes typing.
Syntax
Javascript
function doSomething(callback) {
  // do some work
  callback();
}

doSomething(function() {
  // code to run after work is done
});

The callback is a function passed as an argument.

It runs inside the main function when ready.

Examples
This example greets a person, then runs the callback to say the greeting is done.
Javascript
function greet(name, callback) {
  console.log('Hello ' + name);
  callback();
}

greet('Alice', function() {
  console.log('Greeting done');
});
Here, the callback runs after 1 second delay using setTimeout.
Javascript
setTimeout(() => {
  console.log('Waited 1 second');
}, 1000);
Sample Program

This program simulates fetching data with a 2-second delay. After data is ready, the callback runs and prints the data.

Javascript
function fetchData(callback) {
  console.log('Start fetching data...');
  setTimeout(() => {
    console.log('Data fetched');
    callback('Here is your data');
  }, 2000);
}

fetchData(function(data) {
  console.log('Callback received:', data);
});
OutputSuccess
Important Notes

Callbacks help manage tasks that take time, like loading data.

Without callbacks, code might run too early before tasks finish.

Too many callbacks can make code hard to read, called "callback hell".

Summary

Callbacks are functions passed to other functions to run later.

They help wait for tasks to finish before continuing.

Use callbacks for events, timers, and asynchronous work.