Junior — Middle
In what cases is the concept of closure used in programming?
sobes.tech AI
Answer from AI
Closures in programming are functions that "remember" the context in which they were created, including access to variables from the outer scope even after exiting that scope.
Closures are used in the following cases:
- To create functions with preserved state without using global variables.
- When implementing function factories, where one function returns another with specific parameters.
- To encapsulate logic and data together, for example, in event handlers or callbacks.
- In functional programming to create higher-order functions.
Example in Python:
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
times3 = make_multiplier(3)
print(times3(10)) # Outputs 30
Here, multiplier is a closure that retains the value of factor from the outer function.