All 28 lessons ▾

Inside JavaScript · Lesson 18 of 28

Higher-Order Functions

Updated 11 Nov 2026 · By Akshay, software engineer, India · 9 min read

So, a function that takes another function, or returns one. That's a higher-order function! And it's the secret behind map, filter, and clean code. So let's learn it.

The video for this lesson is coming soon.

A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.

Got a doubt? Ask in the comments under the video.Subscribe

In one minute
  • A higher-order function takes or returns a function
  • The function passed in is the callback
  • Copy-paste loops break DRY
  • Separate the logic from the loop
  • calculate is map: you wrote a polyfill
  • Functional programming: small reusable functions

Part 1What is a higher-order function?

So today's topic sounds fancy. Higher-order functions. But I promise you, you've already used them many times. And by the end of this episode, you'll be writing code like a functional programmer. So let's start with the definition.

REMEMBER THIS
Ahigher-orderfunctiontakesa
functionasanargument,orreturns
one.
the function passed in is the callback

So a higher-order function is a function that takes another function as an argument, or returns a function as its result. Or both. That's it! Simple. And the function that gets passed in? That's our old friend, the callback. So in every callback story, there are two functions. The callback, and the higher-order function that receives it.

hof.js
1function sayHi() {2  console.log("Hi!");3}4 5function run(fn) {6  fn();7}8 9run(sayHi);

Now remember this code from episode thirteen? run takes a function, fn, and calls it. So run is a higher-order function, and sayHi is the callback. setTimeout is a higher-order function too. So is addEventListener. You've been using them all along! And remember makeGreeter, from the closures episode? It returned a function. So it was a higher-order function as well. In fact, most array methods are higher-order functions. forEach, map, filter, reduce, sort, and find. Every one of them takes a function.

Part 2An interview problem

Now let's see why higher-order functions matter, with a kind of problem that's often asked in interviews. So watch how the solution grows.

percent.js
1const marks = [35, 42, 28];2 3function getPercent(marks) {4  const output = [];5  for (let i = 0; i < marks.length; i++) {6    output.push(marks[i] * 2);7  }8  return output;9}

So a teacher has the marks of three students, out of fifty. Thirty five, forty two, and twenty eight. She wants percentages. Easy. We write getPercent. Make an empty output array, loop through the marks, multiply each one by two, push it, and return the output. Seventy, eighty four, fifty six. It works perfectly. Now most people stop here. But the interviewer has more requirements coming.

grace.js
1function addGrace(marks) {2  const output = [];3  for (let i = 0; i < marks.length; i++) {4    output.push(marks[i] + 5);5  }6  return output;7}

Now the principal says, give everyone five grace marks. So what do most people do? Copy getPercent, paste it, rename it addGrace, and change one tiny line. Plus five, instead of times two. Now look at these two functions. They're almost exactly the same! And tomorrow, the school wants a pass or fail list, and a grade for each student. Copy, paste, copy, paste, forever! So this breaks a famous rule called DRY. Don't repeat yourself.

REMEMBER THIS
Separatethelogicfrom
theloop.
the loop is the same; only the logic changes

So here's the trick. Look at what stays the same, and what changes. The loop is the same in every version. Only the logic changes. Times two, plus five, pass or fail. So let's separate them. Write the loop once, and pass the logic in, as a function. And now what do we call a function that takes another function? A higher-order function!

calculate.js
1const percent = function (m) { return m * 2; };2const grace = function (m) { return m + 5; };3 4function calculate(arr, logic) {5  const output = [];6  for (let i = 0; i < arr.length; i++) {7    output.push(logic(arr[i]));8  }9  return output;10}11 12calculate(marks, percent);   // [70, 84, 56]13calculate(marks, grace);     // [40, 47, 33]

So here's the clean version. Each piece of logic is now a tiny function of its own. percent, times two. grace, plus five. And calculate is written only once. It takes an array, and the logic. Inside the loop, it calls logic on each item, and pushes the result. Now one line gives percentages, and another gives grace marks. So need a pass or fail list tomorrow? Just write one tiny function, and pass it in. No copy-paste, ever again.

pass-fail.js
1const passFail = function (m) {2  return m >= 30 ? "pass" : "fail";3};4 5calculate(marks, passFail);   // ["pass", "pass", "fail"]

And now here's tomorrow's requirement, the pass or fail list. Passing is thirty out of fifty. We don't touch calculate at all. We just write one small function, passFail, which checks a single mark. Thirty five, pass. Forty two, pass. Twenty eight, fail. Then hand it to calculate, and we get the whole list. So three requirements, three tiny functions, and one loop. That's the power of separating the logic from the loop.

run-calculate.js
1const marks = [35, 42, 28];2const percent = function (m) { return m * 2; };3 4function calculate(arr, logic) {5  const output = [];6  for (let i = 0; i < arr.length; i++) {7    output.push(logic(arr[i]));8  }9  return output;10}11 12console.log(calculate(marks, percent));
Output
[70, 84, 56]

So let's run it, line by line. First, marks, percent, and calculate are set up in memory. Line twelve calls calculate, and passes two things. The marks array, and the percent function. Inside, arr is the marks, and logic is percent. Line five makes an empty output array. Now the loop. Line seven calls logic with thirty five. logic is percent, so it gives back seventy, and that's pushed. Next, forty two becomes eighty four. And twenty eight becomes fifty six. Line nine returns the output, and the console prints all three. calculate never knew what percent does. It simply called the logic it was given.

Part 3You just wrote map!

Now here's the best part. Look closely at calculate. Do you recognize it? Think.

map.js
1calculate(marks, percent);   // [70, 84, 56]2 3marks.map(percent);          // [70, 84, 56]

It's map! JavaScript's own map does exactly what our calculate does. It loops through the array, calls your function on every item, and returns a new array of results. So you've just built map yourself, from scratch. And that's exactly what interviewers mean when they ask you to write a polyfill. Your own version of a built-in function. And now notice one more thing. map never changes the original array. marks is still thirty five, forty two, twenty eight. So it always gives you a new array.

polyfill.js
1Array.prototype.calculate = function (logic) {2  const output = [];3  for (let i = 0; i < this.length; i++) {4    output.push(logic(this[i]));5  }6  return output;7};8 9marks.calculate(percent);   // [70, 84, 56]

And now we can go one step further. Put calculate on Array.prototype. Now every array in your program gets this method, just like map. Inside it, this refers to the array the method is called on, so marks.calculate, percent, works exactly like marks.map, percent. We'll understand this properly in the this keyword episodes. So for now, just see the power. You've created your own array method! Now one word of caution, though. In real projects, don't add things to built-in prototypes. It's great for learning and interviews, but it can clash with other code.

multiply-by.js
1function multiplyBy(n) {2  return function (m) {3    return m * n;4  };5}6 7const double = multiplyBy(2);8const triple = multiplyBy(3);9 10calculate(marks, double);   // [70, 84, 56]11calculate(marks, triple);   // [105, 126, 84]

Now the other kind of higher-order function, one that returns a function. multiplyBy takes a number n, and returns a brand new function that multiplies by n. So multiplyBy two gives us double, and multiplyBy three gives us triple. And how does double remember that n was two? Closure! It's in the backpack. So here, one higher-order function makes our logic, and another higher-order function, calculate, uses it. Functions making functions, and functions taking functions. So this is functional programming in action.

FUNCTIONAL PROGRAMMING
Smallreusable
functions,passed
aroundasvalues.
the heart of functional
programming
INTERVIEW ANSWER
Ahigher-orderfunction
takesorreturnsa
function,likemap,filter
andsetTimeout.
it separates logic from the loop,
and keeps code DRY

And this style of thinking has a name. Functional programming. So you break your problem into small, reusable functions, each doing one job. And you pass them around as values, to higher-order functions like calculate and map. Each small function is easy to test, and easy to reuse. Your code becomes shorter, cleaner, and so much easier to change. And now notice, our small functions don't change anything outside themselves. They take a value, and return a new one. Functions like that are called pure functions, and they're the safest kind to reuse. So that's what interviewers love to see.

Quick quiz
quiz.js
1function add(a, b) {2  return a + b;3}4function repeat(n, fn) {5  for (let i = 0; i < n; i++) fn();6}7function makeAdder(x) {8  return function (y) {9    return x + y;10  };11}

Which of these are higher-order functions?

Show the answer

So add takes two numbers, and returns a number. No functions involved, so it's not. repeat takes a function, fn, and calls it n times. So yes, it's higher-order. And makeAdder returns a function. So it's higher-order too. Two out of three! Did you get both? And a bonus. Is setTimeout higher-order? Yes, because it takes a function.

Your turn

Where in your code could you use a higher-order function today?

Answer in the comments under the video.

Your progress stays on this device.
A new lesson every day at 11 am

The video on YouTube, and the lesson as a swipe-through on Instagram.