Also written as wrapper function
Higher-Order Functions
JS · Functionssyntax
function fn(callback) { callback(); }
function fn() { return function() {}; }
example
function withLogging(fn) {
return function(...args) {
console.log(`Calling ${fn.name} with`, args);
const result = fn(...args);
console.log(`Result:`, result);
return result;
};
}
const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(3, 4);
output
"Calling add with [3, 4]"
"Result: 7"
Note Functions that accept or return other functions. The backbone of functional patterns like decorators, middleware, and composition.
syntax
@decorator
def func(): ...
example
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return result
return wrapper
@timer
def compute(n):
return sum(range(n))
compute(1_000_000)
output
compute took 0.0XXXs
Note Always use @functools.wraps(func) in your wrapper so that the decorated function preserves its name and docstring. Decorators run at import time.