← Back to JavaScript Course | Chapter 12: Reference & Interview | Lesson 1 of 9

JS Higher Order Functions

What Is a Higher Order Function

A higher-order function either accepts another function as an argument, returns a function, or both — treating functions as ordinary values you can pass around like any other data.

Example: What Is a Higher Order Function

javascript
function repeat(n, action) {
  for (let i = 0; i < n; i++) action(i);
}
repeat(3, console.log); // passing a function as an argument

map

Array.prototype.map() takes a callback and returns a new array where each element is the result of applying that callback to the corresponding original element, leaving the original array unchanged.

Example: map

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

filter

Array.prototype.filter() takes a callback that returns true or false for each element and returns a new array containing only the elements where the callback returned true.

Example: filter

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

reduce

Array.prototype.reduce() takes a callback and an initial value, then repeatedly combines each element into a single accumulated result — useful for sums, groupings, or building any single output from a list.

Example: reduce

javascript
const nums = [1, 2, 3, 4];
console.log(nums.reduce((sum, n) => sum + n, 0));

Combining Higher Order Methods

Because map, filter, and reduce all return new arrays or values, you can chain them together in a single readable pipeline instead of writing separate loops for each transformation step.

Example: Combining Higher Order Methods

javascript
const nums = [1, 2, 3, 4, 5, 6];
const result = nums.filter(n => n % 2 === 0).map(n => n * 10).reduce((sum, n) => sum + n, 0);
console.log(result);
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.