Higher-Order Functions (HOFs)

What is a Higher-Order Function (HOF)?

A Higher-Order Function is a function that does one or both of the following:

  • Takes another function as an argument (input).
  • Returns a function as its output.

It’s like giving instructions to a chef (a function). You can either provide specific ingredients (another function) or let the chef create a custom recipe (return a new function).

Why Use Higher-Order Functions?

  • Code Reusability: Write less, do more!
  • Flexibility: Change the behavior of functions dynamically.
  • Readability: Clearer and more concise code.

Higher-Order Functions (HOFs) and Callback Functions — theory and examples.

Example 1 — Function as Argument (Callback)

Passing a function as an argument and executing it inside another function.

Example 2 — Function Returning Another Function

createMultiplier returns a new function customized by multiplier.

Example 3 — map(), filter(), reduce()

Common HOFs for array transformations & aggregation.

Example 4 — forEach()

Perform action for each array element (no return value).

Example 5 — Callback Demo

Passing greet to processUser and logging result.