Function can return another function just like it can return any other value. This allows functions to create and return customized behavior that can be used later.
Explanation:
- inner() is defined inside outer() and return inner returns the function itself, not the result of calling it.
- func = outer() stores the returned function in func.
- Calling func() executes the inner() function and prints "Hello".
Benefits of Returning Functions
Returning functions makes it possible to create reusable and flexible code. It is commonly used to:
- Create customized functions: Generate functions with specific behavior when needed.
- Preserve data using closures: Inner functions can access values from their enclosing function even after it has finished execution.
- Reduce code duplication: Reuse common logic instead of writing similar functions multiple times.
- Build decorators: Modify or extend the behavior of existing functions.
Examples
Example 1: The following example returns one function from another function and executes it later.
OutputInside method A
Inside method B
Explanation:
- A() returns the function B.
- func = A() stores the returned function in func.
- Calling func() executes B().
Example 2: The following example returns a lambda function that uses values created inside the outer function.
Explanation:
- calc() computes x and y.
- The returned lambda function remembers these values.
- Calling func() returns x * y, which is 21.
Example 3: The following example returns customized functions for different powers.