First-Class & Higher-Order Functions in JavaScript

🟢 Beginner Level | JavaScript Core Syntax

📖 Definition

In JavaScript, functions are First-Class Citizens, meaning they can be stored in variables, passed as arguments to other functions, and returned from functions. A Higher-Order Function (HOF) is any function that accepts another function as an argument or returns a function.

🌍 Multilingual Explanations

English

First-class functions treat functions like any other variable. Higher-Order Functions (like map, filter, reduce) enable functional programming patterns.

Hindi

Higher-Order Function woh function hota hai jo kisi doosre function ko as argument leta hai ya return karta hai.

💡 Production Code Example

// 1. Passing functions as arguments (Callback pattern)
function processTransaction(amount, formatter) {
    const total = amount + 5.00; // adding service fee
    return formatter(total);
}

const usdFormatter = amount => `$${amount.toFixed(2)}`;
console.log(processTransaction(100, usdFormatter)); // "$105.00"

// 2. Returning a function from a Higher-Order Function (Function Factory)
function createMultiplier(multiplier) {
    return function(number) {
        return number * multiplier;
    };
}

const triple = createMultiplier(3);
console.log(triple(10)); // 30

⚠️ Common Pitfalls

Passing Executed Functions instead of References: Writing setTimeout(myFunc(), 1000) executes myFunc() immediately! Write setTimeout(myFunc, 1000) to pass the reference.

🎯 Tiered Practice Exercises

  1. Beginner: Write a Higher-Order Function repeatAction(n, action) that runs the action callback n times.
  2. Intermediate: Build a custom logger factory function createLogger(prefix) returning a prefixed log function.
  3. Advanced: Implement a custom version of Array.prototype.map() from scratch using a Higher-Order Function.

🧭 Navigation

← 03. Parameters, Default Values & Rest Syntax | Functions Hub | 05. Function Scope, Closures & IIFE →