Can someone explain first-class functions, higher-order functions, and closures in JavaScript?
Asked by
MellowCedar47
I've been learning JavaScript for a while and understand how to write and call functions, but I still find three related ideas confusing: first-class functions, higher-order functions, and closures. I understand the basic idea of closures, but I'm having trouble seeing how these concepts connect in actual code. What's a simple way to understand them, preferably with small examples and suggestions for practicing?
Answers
Hereโs one example that combines the ideas: `const makeAdder = amount => number => number + amount;`. `makeAdder` is a higher-order function because it returns another function. The returned function is first-class because it can be stored in a variable: `const addFive = makeAdder(5);`. It is also a closure because it remembers the `amount` value, so `addFive(10)` returns `15`. Try changing the values and logging each step in your browserโs developer tools.
Reply to this answer
The easiest way to learn these is by writing small exercises rather than memorizing definitions. Try passing callbacks to `map`, `filter`, and `setTimeout`, then write a function that returns another function. For closures, create a counter such as `const counter = () => { let value = 0; return () => ++value; };`. Each returned function remembers its own `value`. Use a debugger and inspect the variables while the functions run. Closures usually take more practice because they depend on scope and variable lifetime.
Reply to this answer
A useful distinction is that first-class functions describe what JavaScript allows you to do with functions, while higher-order functions describe a functionโs behavior. First-class means a function can be handled as data. Higher-order means the function works with other functions. Closures describe how a function remembers variables from the scope where it was created. These arenโt three competing types of functions; one function can fit all three descriptions.
Reply to this answer
A first-class function is a function that JavaScript lets you treat like any other value. You can store it in a variable, pass it as an argument, or return it from another function. A higher-order function is a function that accepts another function, returns one, or does both. For example, `array.map(x => x * x)` is higher-order because `map` receives a function. A closure happens when an inner function keeps access to variables from the surrounding function, even after the outer function has finished running.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowCedar47: Thanks, this example makes the connection between the three concepts much clearer. Iโll try experimenting with it.