Skip to content

Latest commit

 

History

History
98 lines (67 loc) · 2.85 KB

File metadata and controls

98 lines (67 loc) · 2.85 KB

Higher-Order function ft Functional Programming

Higher-Order Function — Definition

A Higher-Order Function is a function that either:

  1. Takes one or more functions as arguments
  2. Returns a function as its result
  3. Or both.

💡 Think of it as "functions that operate on other functions."

Example — Takes a function as argument

function greet(name) {
  return `Hello, ${name}`;
}

function processUserInput(callback) {
  const name = 'Alice';
  console.log(callback(name));
}

processUserInput(greet);
// Output: Hello, Alice

Here:

  • processUserInput is a HOF because it accepts greet (a function) as an argument.

Example — Returns a function

function multiplier(factor) {
  return function (number) {
    return number * factor;
  };
}

const double = multiplier(2);
console.log(double(5)); // 10

Here:

  • multiplier is a HOF because it returns another function.

Why Higher-Order Functions Matter

  • They make code more reusable and declarative.
  • Enable abstraction of behavior (you pass what to do instead of how to do it).
  • Essential for functional programming patterns.

Built-in Examples in JavaScript

Many JS array methods are higher-order functions:

const numbers = [1, 2, 3];

numbers.map((num) => num * 2); // HOF → map takes a function
numbers.filter((num) => num > 1); // HOF → filter takes a function
numbers.reduce((a, b) => a + b); // HOF → reduce takes a function

Functional Programming (FP) — Overview

Functional Programming is a programming paradigm where:

  • Computation is treated as the evaluation of pure functions.
  • State and data are immutable.
  • Functions are first-class citizens (can be stored in variables, passed, or returned).
  • Avoids side effects.

Core principles of FP

  1. Pure Functions → Same input → Same output, no side effects.
  2. Immutability → Do not modify existing data; instead, create new data.
  3. Function Composition → Build complex functions from simpler ones.
  4. First-Class Functions → Treat functions like any other variable.
  5. Higher-Order Functions → Use functions to operate on functions.

Example — FP style

// Pure, immutable, declarative
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((x) => x * 2);
console.log(doubled); // [2, 4, 6, 8]

Instead of looping and mutating arrays, FP uses HOFs for cleaner, declarative code.

Interview-Ready Short Answer

A Higher-Order Function is a function that takes one or more functions as arguments, returns a function, or both. They're a key part of functional programming, which treats functions as first-class citizens, avoids side effects, and promotes immutability. Examples include map, filter, reduce. HOFs help abstract behavior, make code reusable, and allow composition of small pure functions into more complex ones.