Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Higher-Order Functions

Higher-order functions work with other functions as inputs or outputs.

They are central to functional programming and modern JavaScript style.

Why We Need It

They let you build reusable behaviors and avoid repetitive loops.

Understanding them makes callbacks, array methods, and composition easier.

Syntax

function apply(value, fn) { ... }
const factory = () => (value) => value;

Basic Example

1. Passing a function

function apply(value, fn) {
  return fn(value);
}

console.log(apply(5, (n) => n * 2));

A function can receive another function as input.

Real World Example

2. Returning a function

function makeMultiplier(factor) {
  return (n) => n * factor;
}

const triple = makeMultiplier(3);
console.log(triple(4));

Return a function configured with a value.

Multiple Use Cases

Functions that Use Functions

A higher-order function takes another function as an argument or returns a function.

This enables reusable, composable logic.

Array Methods

Common higher-order functions include map, filter, and reduce.

They are expressive and reduce boilerplate loops.

Function Factories

Returning a function lets you create specialized behavior.

This is useful for configuration and reuse.

More Examples

3. Array map

const nums = [1, 2, 3];
const squared = nums.map((n) => n * n);

console.log(squared);

map is a higher-order function.

4. Filter

const nums = [1, 2, 3, 4];
const evens = nums.filter((n) => n % 2 === 0);

console.log(evens);

filter uses a callback to decide what to keep.

Comparison

Without

const nums = [1, 2, 3];
const doubled = [];
for (const n of nums) {
  doubled.push(n * 2);
}

With

const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);

Common Mistakes and Fixes

Overcomplicating simple logic

Use higher-order functions when they improve clarity, not by default.

Ignoring performance on large arrays

Be mindful of extra iterations in tight loops.

Anonymous callback confusion

Name functions if callbacks get complex.

Interview Questions

What defines a higher-order function?

Taking a function or returning one.

Give an example of HOF in JS.

Array methods like map or filter.

Why use function factories?

To create specialized functions with shared configuration.

Practice Problem

Practice: Write a function that accepts a number and a formatter callback.

// TODO: function formatNumber(n, formatter)

One Possible Solution

function formatNumber(n, formatter) {
  return formatter(n);
}

console.log(formatNumber(12.3, (v) => v.toFixed(1)));

Frequently Asked Questions

What is a higher-order function?

A function that takes or returns another function.

Are array methods higher-order?

Yes, map, filter, and reduce all take callbacks.

Why use higher-order functions?

They help write reusable and composable logic.

Try It Yourself

Try passing different callbacks to see how results change.