🟨 JavaScript tutorial for beginners · Class 9 · Lesson 8 of 18 · Free
Higher-Order Functions – Pass and Return Functions in JavaScript
⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Store functions in variables and pass them to other functions as callbacks
- Write a function that returns a new, ready-made function
- Build your own versions of map and filter to see how they really work
Your school wants three reports from the same marks list: add grace marks, find toppers, and print report cards. You could write three nearly identical loops. Or you could write ONE loop and hand it a different small function each time. That idea, functions that take or give back other functions, is what this lesson is about.
Can a function be stored in a variable in JavaScript?
Yes. In JavaScript a function is a value, just like a number or a string. You can put it in a variable, an array or an object.
Look closely at the difference: double is the function itself. double(4) RUNS the function and gives its answer.
A function that takes another function as input, or returns one, is called a higher-order function.
▶const double = (n) => n * 2;2const shout = (word) => word.toUpperCase() + "!";34console.log(typeof double);5console.log(double(4));67const tools = [double, shout];8console.log(tools[1]("chalo"));910const sayHi = shout;11console.log(sayHi("namaste"));
No variables yet.
▌✏️ Change this code and run it yourself
function8CHALO!NAMASTE!
💡 Try it: console.log(double) without brackets. You see the function itself, not a result.
How do I pass a function to another function (a callback) in JavaScript?
A callback is a function you give to another function, so it can call it later. You pass the NAME, without brackets.
Below, repeat() does the looping. The callback decides what happens each time. Change the callback and you get new behaviour with the same loop.
You have already used callbacks: forEach, map, filter, addEventListener and setTimeout all take one.
1function repeat(times, action) {2 for (let i = 1; i <= times; i++) {3 action(i);4 }5}67function cheer(n) {8 console.log(`Cheer ${n}: Go India!`);9}▶repeat(3, cheer);1112repeat(2, (n) => console.log(`Diya ${n} lit 🪔`));
No variables yet.
▌✏️ Change this code and run it yourself
Cheer 1: Go India!Cheer 2: Go India!Cheer 3: Go India!Diya 1 lit 🪔Diya 2 lit 🪔
💡 Try it: write your own callback that prints the 7 times table and call repeat(5, yourFunction).
How do map and filter work inside? Can I write my own?
In Lesson 2 you used map and filter. They are higher-order functions too. Writing tiny versions yourself shows there is no magic.
myMap makes a new array and pushes transform(item) for each item. myFilter keeps only the items where test(item) is true.
The loop is written once. Every new job is just a new small function.
[39, 96, 72, 93][91, 88][91, 88]
💡 The last line uses the real filter. It prints the same answer as myFilter.
How can a JavaScript function return another function?
A function can build a new function and return it. Think of a factory that makes custom tools.
makeDiscount(10) returns a function that cuts 10 % off any price. makeDiscount(50) returns a different one. You make each tool once and use it many times.
The returned function remembers the percent it was made with. Lesson 10 (Closures) explains exactly why.
1function makeDiscount(percent) {2 return (price) => price - (price * percent) / 100;3}4▶const diwaliSale = makeDiscount(20);6const clearance = makeDiscount(50);78console.log("Kurta: ₹" + diwaliSale(1000));9console.log("Shoes: ₹" + diwaliSale(2500));10console.log("Old bag: ₹" + clearance(800));
No variables yet.
▌✏️ Change this code and run it yourself
Kurta: ₹800Shoes: ₹2000Old bag: ₹400
💡 Try it: make a studentOffer = makeDiscount(15) and use it on a ₹600 school bag.
How are callbacks used with buttons and timers?
addEventListener is a higher-order function. You give it a callback, and the browser calls it every time the button is clicked.
setTimeout also takes a callback and calls it once, after a delay. Here one named function, showLight, is used by BOTH.
Click the button on the page and watch the console.
📄 HTML of the page (tap to see / edit)
Diyas lit: 1
💡 Write showLight, not showLight(). With brackets the function would run once right away, and the button would get its result instead.
How do I combine small functions into a pipeline?
Because functions are values, you can keep a list of steps and run them one after another.
pipe() below takes any number of functions (rest from Lesson 7) and returns ONE new function that runs them in order.
This is how many real apps clean up data: small, tested steps joined together.
aarav_sharmapriya_k
💡 Try it: change the order of steps in pipe(...) and see if the result changes.
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
function twice(fn, x) {
return fn(fn(x));
}
console.log(twice((n) => n + 3, 1));Question 2. What does this print?
const add = (a) => (b) => a + b; console.log(add(10)(5));
Question 3. What does this print?
const sayHi = () => "Hi"; console.log(typeof sayHi, typeof sayHi());
🧩 Your challenge
Write a marks processor. 1) applyToAll(list, fn) returns a NEW array with fn applied to each mark (do not use map — write the loop). 2) makeGrace(extra) returns a function that adds extra marks but never goes above 100. 3) Use them to add 5 grace marks to [38, 97, 64, 99]. Expected output: With grace: [43, 100, 69, 100] Original: [38, 97, 64, 99]
With grace: [43, 100, 69, 100] Original: [38, 97, 64, 99]
⚠️ Common mistakes (and how to fix them)
❌ Wrong
const double = (n) => n * 2; const marks = [10, 20]; console.log(marks.map(double()));
TypeError: number NaN is not a function
✅ Right
const double = (n) => n * 2; const marks = [10, 20]; console.log(marks.map(double));
double() runs the function right away (with no number, so NaN) and passes that result. Pass the function itself: double, without brackets.
❌ Wrong
const marks = [10, 20, 30];
const bonus = marks.map((m) => { m + 5; });
console.log(bonus);No error, but it prints [undefined, undefined, undefined]: the callback has braces and no return, so it returns nothing.
✅ Right
const marks = [10, 20, 30]; const bonus = marks.map((m) => m + 5); console.log(bonus);
With { } an arrow function needs the word return. Without braces, the value is returned automatically.
❌ Wrong
function runTwice(callback) {
callback();
callback();
}
runTwice();TypeError: callback is not a function
✅ Right
function runTwice(callback) {
callback();
callback();
}
runTwice(() => console.log("Run!"));The callback was never given, so it is undefined, and undefined cannot be called. Always pass a function when one is expected.
📌 Remember
- In JavaScript, functions are values: store them in variables, arrays and objects.
- A higher-order function takes a function as input or returns one.
- Pass a callback by name without brackets: fn, not fn().
- map, filter, forEach, addEventListener and setTimeout are all higher-order functions.
- A function can return a new custom function, like makeDiscount(20).
- Small functions joined together (a pipeline) keep code short and easy to change.
Finished the quiz and the challenge?
Questions students ask
What is a higher-order function in JavaScript?
It is a function that takes another function as an argument, or returns a function, or both. Array methods like map and filter are common examples. They let you write a loop once and change only the small part that differs.
What is a callback function?
A callback is a function passed into another function to be called later. For example, in button.addEventListener("click", showMenu), showMenu is the callback. The browser calls it each time the button is clicked.
Why do I write fn and not fn() when passing a function?
fn is the function itself, so the other function can call it when it wants. fn() calls it immediately and passes only the result. Most of the time you want to pass the function, not its result.
Are higher-order functions hard for Class 9?
Not if you take it step by step. If you can write a function and use map or forEach, you already use them. Practise by writing your own myMap and myFilter, like in this lesson.