🔍

Closures and Higher-Order Functions



Introduction to Closures and Higher-Order Functions

Closures and higher-order functions are two foundational concepts in functional programming. Together, they enable powerful patterns like function factories, partial application, and data encapsulation.

What is a Closure?

A closure is a function that "remembers" variables from its lexical scope even when it's executed outside of that scope.

To put it simply, if an inner function uses variables from an outer function, and the inner function is returned or passed around, it "closes over" those variables, keeping them alive.

Example: Closure that Remembers

function makeCounter():
    count = 0

    function increment():
        count = count + 1
        return count

    return increment

counterA = makeCounter()
print(counterA())  # 1
print(counterA())  # 2

counterB = makeCounter()
print(counterB())  # 1

Output:

1
2
1

Explanation

The inner function increment() "remembers" the value of count from its outer function makeCounter(), even after makeCounter() has finished executing. This is a closure.

Question:

Why does counterB() start from 1 again?

Answer: Because each call to makeCounter() creates a new scope with its own count. Each closure maintains its own private memory.

What is a Higher-Order Function?

A higher-order function is a function that either:

These functions allow us to abstract over actions, not just values.

Example: Passing Function as an Argument

function double(x):
    return x * 2

function applyFunction(f, value):
    return f(value)

result = applyFunction(double, 5)
print(result)

Output:

10

Here, applyFunction is a higher-order function because it takes another function double as input.

Example: Returning a Function (Function Factory)

function createMultiplier(factor):
    function multiply(x):
        return x * factor
    return multiply

times3 = createMultiplier(3)
print(times3(4))  # 12

times10 = createMultiplier(10)
print(times10(2))  # 20

Output:

12
20

This is a classic closure + higher-order function pattern: createMultiplier returns a function that retains access to the factor passed to it. Each returned function has its own enclosed environment.

Question:

How is this useful in real scenarios?

Answer: Closures and higher-order functions allow us to create configurable functions (like times3 or times10) and reduce repetition in code, improving modularity and reusability.

Recap

Practice Thought

Try writing a function that keeps a running total and returns it every time it’s called. Can you implement it using closures?



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M