DEV Community

Cover image for Closures: A Powerful Concept in JavaScript
koushikmaratha
koushikmaratha

Posted on • Edited on

Closures: A Powerful Concept in JavaScript

Closures are a powerful concept in JavaScript that can be confusing for beginners to understand. However, once you understand closures, you can take advantage of them to write more efficient and effective code. In this article, we will explore what closures are, how they work, and how they can be used in JavaScript.

What are closures?

A closure is a function that has access to variables from its outer lexical scope, even after the outer function has returned. In other words, a closure allows a function to access variables in its outer function even when the outer function has finished executing. This is possible because JavaScript creates a new execution context for each function, which has access to its parent execution context.

How do closures work?

In JavaScript, functions are first-class citizens, which means they can be passed around as values just like variables. When a function is executed, a new execution context is created, which includes a new variable environment that contains any variables declared within the function. However, if a function declares a variable that is not within its scope, JavaScript will look for the variable in the parent scope until it finds it.

When a function is defined inside another function, it creates a closure. The inner function has access to the outer function's variables and parameters, even after the outer function has returned. This is because the inner function retains a reference to the outer function's variables, which are stored in the closure.

How can closures be used?

Closures can be used in a variety of ways in JavaScript. One common use case for closures is to create private variables and methods. For example, consider the following code:

function counter() {
  let count = 0;

  return function() {
    count++;
    console.log(count);
  }
}

const increment = counter();

increment(); // logs 1
increment(); // logs 2
increment(); // logs 3

Enter fullscreen mode Exit fullscreen mode

In this example, the counter function returns an inner function that has access to the count variable. When the inner function is executed, it increments the count variable and logs its value. Because the count variable is declared within the counter function, it is not accessible from outside the function. This creates a private variable that can only be accessed through the closure.

Closures can also be used to create functions that remember their context. For example, consider the following code:

function greeting(name) {
  return function() {
    console.log(`Hello, ${name}!`);
  }
}

const greetJohn = greeting('John');
const greetMary = greeting('Mary');

greetJohn(); // logs "Hello, John!"
greetMary(); // logs "Hello, Mary!"

Enter fullscreen mode Exit fullscreen mode

In this example, the greeting function returns an inner function that logs a greeting with the name passed to the outer function. The greetJohn and greetMary variables store references to the inner function returned by greeting, and when they are executed, they log a greeting with the appropriate name. Because the inner function has access to the name variable, it remembers its context and can log the appropriate name even after the outer function has returned.

Conclusion

Closures are a powerful concept in JavaScript that can be used to create private variables and methods, as well as functions that remember their context. By understanding how closures work and how they can be used, you can write more efficient and effective code.

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You might want to consider re-wording this:

A closure is a function that has access to variables from its outer lexical scope...

ALL functions have access to variables from their outer lexical scope. A closure and a function are two different things. From MDN:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

The distinction is slight, but saying that a closure is a function just generates the incorrect perception that a closure is some kind of special type of function - which is not the case at all. I'm not sure where this misunderstanding comes from - maybe a lot of JS courses are teaching it weirdly?

Also, you have a glaring typo in the header image 😱

Collapse
 
koushikmaratha profile image
koushikmaratha

Hi, @jonrandy

The statement "a closure is not a function" is true in the sense that a closure is not a standalone entity that can be invoked like a function. Rather, a closure is a behavior that arises from the way functions access variables from their outer lexical scope.

So, When a function accesses a variable from its outer scope, a reference to that variable is stored in the function's closure. This allows the function to maintain access to the variable even after the outer scope has been destroyed. In essence, a closure is a way for a function to "remember" the state of its outer scope at the time it was created.

Therefore, while a closure is not a standalone function, it is a behavior that is closely tied to the way functions work and their access to variables in their outer lexical scope.