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:

function outerFunction() {
  let message = "Hello from outer";

  function innerFunction() {
    console.log(message); // InnerFunction 'borrows' and logs 'message'
  }

  return innerFunction; // Return the nested function
}

const myClosure = outerFunction(); 
myClosure(); // Output: Hello from outer (closure still has access)

Explanation:

  1. outerFunction(): Defines a variable message.

  2. innerFunction(): Accesses and logs the message variable from the enclosing outerFunction scope, even after outerFunction() has finished.

  3. Return innerFunction(): The outerFunction returns the innerFunction, 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