create a closure in javascript

In JavaScript, a closure is created when an inner function has access to the variables of its outer function, even after the outer function has finished executing. To create a closure in JavaScript, you need to define a function inside another function that has access to variables declared in the outer function.

Here's an example:

index.tsx
function outerFunction() {
  let outerVariable = 10;

  function innerFunction() {
    console.log(outerVariable); // Logs 10
  }

  return innerFunction;
}

let closure = outerFunction();
closure(); // Logs 10
211 chars
13 lines

In the above example, innerFunction is defined inside outerFunction, and has access to the outerVariable variable. When outerFunction is called and its return value is assigned to closure, it returns innerFunction. Later, when closure is invoked, it still has access to outerVariable, which logs 10 to the console.

Closures take advantage of JavaScript's lexical scoping, which means that functions can access variables in their outer (enclosing) scope, even after the outer function has finished executing.

You can also create closures with anonymous functions, like this:

index.tsx
let outerVariable = 10;

let closure = function() {
  console.log(outerVariable); // Logs 10
}

closure();
107 chars
8 lines

In this example, the anonymous function has access to outerVariable, and logs 10 to the console when it is invoked.

gistlibby LogSnag