⬅ Previous Topic
Immutability and Pure FunctionsNext Topic ⮕
What is Asynchronous Programming?⬅ Previous Topic
Immutability and Pure FunctionsNext Topic ⮕
What is Asynchronous Programming?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.
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.
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
The inner function increment()
"remembers" the value of count
from its outer function makeCounter()
, even after makeCounter()
has finished executing. This is a closure.
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.
A higher-order function is a function that either:
These functions allow us to abstract over actions, not just values.
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.
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.
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.
Try writing a function that keeps a running total and returns it every time it’s called. Can you implement it using closures?
⬅ Previous Topic
Immutability and Pure FunctionsNext Topic ⮕
What is Asynchronous Programming?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.