closure in javascript

In JavaScript, a closure is a function that has access to variables in an outer or parent function's scope chain. Closures can be used to capture state and create private variables or functions.

index.tsx
function outerFunction() {
  let outerVariable = "I am outside!";

  function innerFunction() {
    let innerVariable = "I am inside!";
    console.log(innerVariable, outerVariable); // I am inside! I am outside!
  }
  return innerFunction;
}

let closure = outerFunction();
closure();
286 chars
13 lines

In this example, outerFunction creates a closure when innerFunction is returned. innerFunction can access outerVariable even though it was declared in a different scope. When outerFunction is called, it returns innerFunction and assigns it to closure. Finally, when closure is invoked, it logs the values of innerVariable and outerVariable.

gistlibby LogSnag