DEV Community

Cover image for Higher-Order Functions in JavaScript
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on • Originally published at dev.to

Higher-Order Functions in JavaScript

What is a Higher-Order Function (HOF)?
A higher-order function is a function that:

Takes one or more functions as arguments.
Returns a function as its result.
This concept allows us to write modular and reusable code.
Examples include map(),filter(), and reduce().

Example 1: Basic Higher-Order Function

function callbackFunction() {
    console.log('I am a callback function');
}

function higherOrderFunction(func) {
    console.log('I am a higher-order function');
    func();
}

higherOrderFunction(callbackFunction);

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Here, higherOrderFunction() is a HOF because it accepts callbackFunction() as an argument.

Benefits of Higher-Order Functions
HOFs make code:

Concise: Avoid repetitive logic.
Reusable: Write logic once, use it multiple times.
Modular: Keep different functionalities separate.
Example 2: Using HOFs to Avoid Repetition

Without HOFs.

const radius = [1, 2, 3];

function calculateArea(radius) {
    return radius.map(r => Math.PI * r * r);
}

function calculateDiameter(radius) {
    return radius.map(r => 2 * r);
}

console.log(calculateArea(radius));
console.log(calculateDiameter(radius));

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

With HOFs:

const radius = [1, 2, 3];

const area = r => Math.PI * r * r;
const diameter = r => 2 * r;

function calculate(radius, logic) {
    return radius.map(logic);
}

console.log(calculate(radius, area));
console.log(calculate(radius, diameter));

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Using a HOF (calculate()), we’ve generalized the computation. Adding new operations, like circumference, becomes straightforward.

Key Built-In Higher-Order Functions

1.map()
Transforms elements of an array based on a callback function.
Example 1: Adding 10 to each element.

const arr = [1, 2, 3, 4];
const output = arr.map(num => num + 10);

console.log(output); // [11, 12, 13, 14]

Enter fullscreen mode Exit fullscreen mode

Example 2: Extracting user names

const users = [
    { firstName: 'John', lastName: 'Doe' },
    { firstName: 'Jane', lastName: 'Doe' }
];

const names = users.map(user => `${user.firstName} ${user.lastName}`);
console.log(names); // ['John Doe', 'Jane Doe']

Enter fullscreen mode Exit fullscreen mode

2. filter()
Filters elements of an array based on a condition.
Example 1: Filtering odd numbers.

const arr = [1, 2, 3, 4];
const oddNumbers = arr.filter(num => num % 2 !== 0);

console.log(oddNumbers); // [1, 3]

Enter fullscreen mode Exit fullscreen mode

Example 2: Users older than 30

const users = [
    { firstName: 'John', age: 25 },
    { firstName: 'Jane', age: 35 }
];

const adults = users.filter(user => user.age > 30);
console.log(adults); // [{ firstName: 'Jane', age: 35 }]

Enter fullscreen mode Exit fullscreen mode

3. reduce()
Reduces an array to a single value using a callback function.
Example 1: Summing numbers.

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10

Enter fullscreen mode Exit fullscreen mode

Example 2: Finding the maximum value

const numbers = [1, 20, 3, 4];

const max = numbers.reduce((max, curr) => (curr > max ? curr : max));
console.log(max); // 20

Enter fullscreen mode Exit fullscreen mode

Example 3: Merging objects

const objArray = [{ a: 1 }, { b: 2 }, { c: 3 }];

const merged = objArray.reduce((acc, obj) => ({ ...acc, ...obj }), {});
console.log(merged); // { a: 1, b: 2, c: 3 }

Enter fullscreen mode Exit fullscreen mode

Use Cases.

  • Data Transformation: Use map() for transforming data.
  • Filtering Data: Use filter() for conditional selection.
  • Aggregations: Use reduce() for operations like summing, grouping, or merging data.

Top comments (0)