Closure Functions
Posted on Fri 21 May 2021 in Programming • 1 min read • first-class functions python luajit javascript
Closure are higher-order functions which return lower-order function (usually first-order function) with its environment. Defining closure functions is possible in languages which has first-class functions like Python, JavaScript, Lua, Scheme, and others.
Example
1 2 3 4 5 6 |
|
This closure function (divisiblity_check
) is return another function as evident by syntax. It should be noted that environment for inner function (i.e., the variable divisor
) is also saved with the returned function. Hence, following line of codes work:
1 2 3 4 5 6 7 |
|
Here, although the functions div_by_7
and div_by_19
are returned by same closure function; however they have different environment attached to them and hence produce different results. The example closure function (i.e., divisiblity_check
) can also be defined using anonymous function.
1 2 3 4 |
|
This usage is sometimes called anonymous closure function.