Module 12 // Core JavaScript

Higher-Order Functions

Module Objective

Functions as values, callbacks, composition, currying basics

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Building Reusable Logic
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;

function applyOp(x, y, op) {
  console.log("Applying operation...");
  return op(x, y);
}

console.log(applyOp(5, 3, add));      // 8
console.log(applyOp(5, 3, multiply)); // 15
💡 `applyOp` is a HOF because it treats logic (the `op` function) as data that can be swapped out easily.
// Example 2
// 2. Factory Pattern
function createLogger(level) {
  return (msg) => console.log(`[${level.toUpperCase()}] ${msg}`);
}

const info = createLogger('info');
const error = createLogger('error');

info('System started'); // "[INFO] System started"
error('Connection lost'); // "[ERROR] Connection lost"
💡 HOFs can 'specialize' a function. `createLogger` returns a new function that 'remembers' the `level` it was created with (using a closure).
// Example 3
// 3. Built-in HOFs: Array methods
const prices = [10, 20, 30];

// map, filter, and reduce are ALL higher-order functions
const taxed = prices.map(p => p * 1.15); 
console.log(taxed);
💡 Most functional methods in JS are HOFs because they accept callbacks to define how the data should be handled.

Engine & Memory Architecture

HOFs in Memory

1. Functional Scope:

  • Returning a function creates a Closure.
  • The returned function maintains a reference to the Lexical Environment of its parent, keeping those variables alive in the Heap.

2. Garbage Collection:

  • Even if the HOF (parent) has finished executing, its memory isn't reclaimed as long as the returned (child) function is still accessible.

3. Optimization:

  • Modern engines can inline simple HOFs during JIT Compilation, reducing the performance cost of multiple function calls.