Skip to content

JavaScript Tutorial Functions

JavaScript Callback Functions

Lesson 57 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

A callback is a function you pass to another function, so that function can call it at the right time. The name comes from “call me back when you are ready”.

script.js
JS
function greet(name, callback) {
  console.log("Hello, " + name);
  callback();
}

greet("Maya", function () {
  console.log("Nice to meet you!");
});

Output: Hello, Maya, then Nice to meet you!. The greet function decides when the callback runs. You decide what it does.

You already use callbacks

Array methods take callbacks:

script.js
JS
const prices = [10, 20, 30];

prices.forEach(price => console.log(price));
const withTax = prices.map(price => price * 1.2);
console.log(withTax); // → [12, 24, 36]

So do events:

script.js
JS
button.addEventListener("click", () => {
  console.log("Clicked");
});

And timers:

script.js
JS
setTimeout(() => console.log("Done waiting"), 500);
console.log("This prints first");

Passing a named function

A callback can be a function you defined earlier, as long as you pass it without parentheses.

script.js
JS
function shout(text) {
  return text.toUpperCase() + "!";
}

console.log(["hi", "hey"].map(shout)); // → ["HI!", "HEY!"]

Writing a function that takes a callback

script.js
JS
function repeat(times, action) {
  for (let i = 0; i < times; i++) {
    action(i);
  }
}

repeat(3, i => console.log("Step", i));

Callbacks and waiting

Callbacks were the original way to handle code that finishes later, such as loading a file or waiting for a server. That works, but long chains get hard to read, which led to promises and async/await. See Callbacks and Their Problems later.

lightbulb
Name the callback parameter
Parameter names like callback, onSuccess or handler make the purpose obvious to anyone reading your function.