A callback function is a function that is passed as an argument to another function. The receiving function can execute the callback when it needs it.
A callback function is a function passed to another function as an argument.
function greet(
callback: () => void
): void {
callback();
}
function message(): void {
console.log("Hello");
}
greet(message);
Here, message is passed to greet()
as a callback.
Callback functions allow us to create flexible and reusable functions.
A callback can be declared as a function parameter.
function process(
callback: () => void
): void {
callback();
}
The type () => void means that the callback
takes no parameters and does not return a value.
A named function can be passed as a callback.
function showMessage(): void {
console.log("Welcome");
}
function execute(
callback: () => void
): void {
callback();
}
execute(showMessage);
Arrow functions are commonly used as callbacks.
function execute(
callback: () => void
): void {
callback();
}
execute(() => {
console.log("Hello TypeScript");
});
A callback can receive parameters.
function processName(
name: string,
callback: (value: string) => void
): void {
callback(name);
}
processName(
"Amit",
value => {
console.log(
"Hello " + value
);
}
);
A callback can receive a number from the calling function.
function processNumber(
number: number,
callback: (value: number) => void
): void {
callback(number);
}
processNumber(
10,
value => {
console.log(
value * 2
);
}
);
Output:
20
A callback can also return a value.
function calculate(
number: number,
callback: (value: number) => number
): number {
return callback(number);
}
const result = calculate(
10,
value => value * 2
);
console.log(result);
Output:
20
A callback can receive more than one parameter.
function calculate(
a: number,
b: number,
callback: (
x: number,
y: number
) => number
): number {
return callback(a, b);
}
console.log(
calculate(
10,
20,
(x, y) => x + y
)
);
A type alias can make callback types easier to reuse.
type Calculator = (
a: number,
b: number
) => number;
function calculate(
a: number,
b: number,
operation: Calculator
): number {
return operation(a, b);
}
We can pass an addition function as a callback.
type Operation = (
a: number,
b: number
) => number;
function calculate(
a: number,
b: number,
operation: Operation
): number {
return operation(a, b);
}
const add: Operation = (
a,
b
) => a + b;
console.log(
calculate(10, 20, add)
);
The same function can accept a multiplication callback.
type Operation = (
a: number,
b: number
) => number;
const multiply: Operation = (
a,
b
) => a * b;
console.log(
calculate(
10,
20,
multiply
)
);
The forEach() array method accepts a callback.
const numbers: number[] = [
10,
20,
30
];
numbers.forEach(
number => {
console.log(number);
}
);
The arrow function is the callback.
The map() method uses a callback to transform
every array element.
const numbers: number[] = [
1,
2,
3
];
const doubled = numbers.map(
number => number * 2
);
console.log(doubled);
Output:
[2, 4, 6]
The filter() method uses a callback to decide
which elements should remain in the array.
const numbers: number[] = [
10,
15,
20,
25
];
const result = numbers.filter(
number => number > 15
);
console.log(result);
Output:
[20, 25]
The reduce() method uses a callback to combine
array values into one result.
const numbers: number[] = [
10,
20,
30
];
const total = numbers.reduce(
(sum, number) =>
sum + number,
0
);
console.log(total);
Output:
60
A callback can be executed later using
setTimeout().
setTimeout(
() => {
console.log(
"Hello after 2 seconds"
);
},
2000
);
The arrow function is passed as a callback.
A callback can process a string supplied by another function.
function processText(
text: string,
callback: (value: string) => string
): string {
return callback(text);
}
const result = processText(
"hello",
value => value.toUpperCase()
);
console.log(result);
Output:
HELLO
Callback functions can be used to process student marks.
function processMarks(
marks: number[],
callback: (mark: number) => number
): number[] {
return marks.map(
mark => callback(mark)
);
}
const marks = [
50,
60,
70
];
const updatedMarks =
processMarks(
marks,
mark => mark + 5
);
console.log(updatedMarks);
Output:
[55, 65, 75]
A callback can receive an object.
type Student = {
name: string;
marks: number;
};
function showStudent(
student: Student,
callback: (value: Student) => void
): void {
callback(student);
}
showStudent(
{
name: "Amit",
marks: 85
},
student => {
console.log(
student.name
);
}
);
A callback can receive an optional value.
function greet(
name: string | undefined,
callback: (
value?: string
) => void
): void {
callback(name);
}
greet(
undefined,
value => {
console.log(
value ?? "Guest"
);
}
);
React components commonly receive callback functions through props.
type ButtonProps = {
onClick: () => void;
};
function MyButton(
props: ButtonProps
) {
return (
<button onClick={props.onClick}>
Click
</button>
);
}
The onClick prop is a callback function.
React Native components frequently use callback functions for user interactions.
type ButtonProps = {
onPress: () => void;
};
function handlePress(): void {
console.log(
"Button Pressed"
);
}
The handlePress function can be passed to
a React Native button's onPress property.
Event handlers can receive event information through callback functions.
type ChangeHandler = (
value: string
) => void;
const handleChange: ChangeHandler = (
value
) => {
console.log(
"Value: " + value
);
};
This pattern is useful when creating reusable form components.
A callback can receive multiple arguments.
function calculate(
a: number,
b: number,
callback: (
x: number,
y: number
) => void
): void {
callback(a, b);
}
calculate(
10,
20,
(x, y) => {
console.log(
"Total: " + (x + y)
);
}
);
A callback can also accept a variable number of arguments.
type NumberCallback = (
...numbers: number[]
) => number;
const total: NumberCallback = (
...numbers
) => {
return numbers.reduce(
(sum, number) =>
sum + number,
0
);
};
console.log(
total(10, 20, 30)
);
A common mistake is calling the function immediately instead of passing the function itself.
function execute(
callback: () => void
): void {
callback();
}
function showMessage(): void {
console.log("Hello");
}
// Correct
execute(showMessage);
// Also possible
execute(() => showMessage());
When passing a callback by name, use
showMessage, not showMessage().
Callback functions are useful when:
This example uses a callback to calculate a student's result.
type ResultCallback = (
total: number,
average: number
) => void;
function calculateResult(
marks: number[],
callback: ResultCallback
): void {
const total = marks.reduce(
(sum, mark) =>
sum + mark,
0
);
const average =
total / marks.length;
callback(
total,
average
);
}
calculateResult(
[80, 75, 90, 85],
(total, average) => {
console.log(
"Total: " + total
);
console.log(
"Average: " + average
);
}
);
Output:
Total: 330
Average: 82.5
A callback function is a function passed to another function so that it can be executed when required.
function execute(
callback: () => void
): void {
callback();
}
execute(() => {
console.log("Done");
});
TypeScript function types make callback functions safer by defining their parameters and return values.
forEach(), map(), filter(), and reduce() use callbacks.Question: What is a callback function?