What is closure?

Asked by: tomlance79
Date:
Viewed: 353
Answers: 1
  • 0

What is a closure in Javascript?

Answers

Answer by: jenniryan

Answered on: 21 Jul 2023

  • 0

In JavaScript, a closure is a function that retains access to the variables in its lexical scope, even when the function is executed outside that lexical scope. This is possible because of the way that JavaScript handles variable scopes and the fact that functions in JavaScript are first-class objects, which means that they can be assigned to variables, passed as arguments to functions, and returned as values from functions.

Here is a simple example of a closure in JavaScript:

function createCounter() {
   let count = 0;
   return function() {
      count += 1;
      return count;
   }
}

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

In this example, the createCounter function returns a function that increments a counter variable and returns its value. The returned function has access to the count variable, even though it is executed outside the lexical scope of the createCounter function. This allows the returned function to maintain state between invocations.

Closures are a powerful feature of JavaScript and are used in many different ways, such as to create private variables, to create callback functions, and to implement functional programming techniques.

Please log in to post an answer!