Explain the concept of closures in JavaScript

Experience Level: Medior
Tags: JavaScript

Answer

A closure is a feature in JavaScript that allows a function to access variables from its outer lexical environment, even after the outer function has returned. In simpler terms, a closure is a function that has access to variables in its outer scope, even after the outer function has completed execution. This is achieved by creating a reference to the outer variable in the inner function, which is then stored in memory.

One of the most common use cases for closures is to create private variables and methods in JavaScript. This is done by defining a function that returns an object with methods that have access to the private variables. The private variables are defined in the outer function, and are only accessible to the inner functions through the closure.

Here's an example of how closures can be used to create private variables and methods:


function counter() {
  let count = 0;
  
  return {
    increment: function() {
      count++;
    },
    decrement: function() {
      count--;
    },
    getCount: function() {
      return count;
    }
  }
}

const myCounter = counter();
myCounter.increment();
myCounter.increment();
console.log(myCounter.getCount()); // Output: 2

In this example, the `counter` function returns an object with three methods: `increment`, `decrement`, and `getCount`. The `count` variable is defined in the outer function, and is only accessible to the inner functions through the closure. This allows us to create a counter that is private and can only be accessed through the methods provided by the `counter` function.

Related JavaScript job interview questions

Comments

No Comments Yet.
Be the first to tell us what you think.