Abstract
- Closure is a Function inside a function that remembers and has access to variables that are outside of itself, even after the outer function finishes executing. It is like creating an instance of a function. The code editor below shows a simple example
Where is
inner_func
whenouter_func()
finishes executing?The
inner_func
closure is stored in the Heap Segment when it is created insideouter_func()
. This also means that closure takes up Main Memory resources!!!
Since closure depends on external variables, so it isn't pure function?
Closure is Pure Function if the external variables it depends on is immutable and it maintains Referential Transparency.
Data Encapsulation with Closure
- Data encapsulation with closure means creating private variables within a function scope that cannot be accessed directly from the outside. These private variables can only be accessed and modified through the functions defined within the same scope
- In the code example below,
createBankAccount()
is the function scope,balance
is the private variable.deposit()
,withdraw()
&getBalance()
are functions defined within the same scope. We are unable to accessbalance
directly from outside of thecreateBankAccount
as shown withconsole.log(myAccount.balance);
at the last line of the program. We can only access it withdeposit()
,withdraw()
&getBalance()
Better codes!
Data Encapsulation with Closure prevents exposing important data when it isn’t needed, accessing and modifying important data can only be done via a set functions which can enforce some checks!