User Tools

Site Tools


java-script:closures

Java Script Closures

A closure is a function that remembers the variables and scope of its outer (enclosing) function, even after the outer function has finished executing.
It “closes over” the variables it needs, hence the name “closure.”

Usages and properties:

  1. Lexical Scoping: JavaScript uses lexical scoping, which means that the scope of a variable is determined by its location in the source code (i.e., where it is defined) and nested functions have access to variables defined in their containing (enclosing) functions.
  2. Function and Inner Function: In JavaScript, you can define functions inside other functions, and these inner functions have access to the variables declared in their outer function.
  3. Returning Functions: When a function returns another function (or an object containing functions), the inner function maintains a reference to the variables of the outer function even after the outer function has finished executing. This is where the closure is formed.
  4. Private Data: Closures allow you to create private data and encapsulate functionality. Variables defined within the outer function are not directly accessible from outside, but the inner function has access to these variables, creating a private scope for those variables.
  5. Callbacks and Event Handlers: Closures are commonly used with callbacks and event handlers, enabling functions to “remember” and maintain their context even when called later.

Example:

function outerFunction() {
  let outerVariable = 'I am from the outer function';
 
  function innerFunction() {
    console.log(outerVariable);
  }
 
  return innerFunction;
}
 
const closureExample = outerFunction();
closureExample(); // Outputs: "I am from the outer function"
java-script/closures.txt · Last modified: 2023/07/26 17:26 by odefta