Skip to main content
TOPIC 4 OF 9 · 2 MIN READ

Callback Functions and Higher-Order Functions

Functions in JavaScript can be passed as arguments or returned from other functions. Callback functions and higher-order functions make this possible, providing powerful tools for asynchronous programming.

What you will learn

  • Define callback and higher-order functions.
  • Understand their relationship.
  • Learn to use callbacks in JavaScript.

Key concepts

Callback Function

A function passed as an argument to another function.

Example
function greet(name) {
  console.log(`Hello, ${name}`);
}
function processUserInput(callback) {
  let name = 'Alice';
  callback(name);
}
processUserInput(greet);

Higher-Order Function

A function that takes other functions as arguments or returns them.

Example
function higherOrder(fn) {
  fn();
}
higherOrder(() => console.log('Callback executed!'));

Step by step

Defining Callbacks:

  • Create a function to handle a task.

Passing Callbacks:

  • Use callbacks to decouple logic.

Higher-Order Functions:

  • Functions like map, filter, and reduce are built-in higher-order functions.

Examples

Using map:

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6]

Practise it

Try these without looking back. If you can explain each one out loud, you are ready for this question.

  • Write a higher-order function that accepts a callback to perform operations on numbers.
  • Use filter to extract even numbers from an array.

Summary

Callbacks and higher-order functions enable flexible and reusable code structures, essential for modern JavaScript programming.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus