Question 78
Question
Explain the concept of function borrowing in JavaScript.
Answer
What is Function Borrowing?
Function borrowing (also known as "closures") happens when a nested function within an outer function accesses and potentially modifies variables from its surrounding scope, even after the outer function has finished executing. The inner function essentially "borrows" these variables, creating a persistent connection to them.
Key Points:
Closures: A closure is formed when a nested function retains access to the lexical environment (variables and functions) where it was defined, even after the outer function has completed its execution.
Lexical Scope: JavaScript uses lexical scoping, meaning variables are looked up based on the function's definition location, not the point of execution.
Example:
Explanation:
outerFunction()
: Defines a variablemessage
.innerFunction()
: Accesses and logs themessage
variable from the enclosingouterFunction
scope, even afterouterFunction()
has finished.Return
innerFunction()
: TheouterFunction
returns theinnerFunction
, allowing us to call it later.
Uses of Function Borrowing:
Data Encapsulation: Protect variables within a function's scope (e.g., creating private variables).
State Management: Maintain state between function calls, making functions "remember" values from previous executions.
Last updated