DEV Community

Cover image for Understanding Closures in JavaScript
Ajisafe Oluwapelumi
Ajisafe Oluwapelumi

Posted on

Understanding Closures in JavaScript

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 us access to an outer function's scope from an inner function. In this post, we'll take a dive into closures, explaining what they are, how they work, and how to use them in our code.

What is a Closure?

A closure is created when a function is defined inside another function and it has access to the variables of the outer function, even after the outer function has returned. This is because the inner function retains a reference to the environment in which it was created.

Game of Throne reference about how the North and Closures remember

Why Use Closures?

Closures can be used to create private variables and functions. This is useful for writing more robust and organized code especially in complex projects where code organization is critical.

Side Eye Meme on how closures work

How Closures Work?

To understand how closures work, it's important to understand the concept of scope in JavaScript. Every function has its own scope, which defines the variables and parameters that are accessible within that function. When a function is defined inside another function, it has access to the variables and parameters of the outer function, but not the other way around.

Here is an example to see how closures work:

function outer() {
  let count = 0;

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

  return inner;
}

let closureFunction = outer();
closureFunction(); // Output: 1
closureFunction(); // Output: 2
closureFunction(); // Output: 3
Enter fullscreen mode Exit fullscreen mode

In this example, the outer function creates a variable count and defines an inner function inner that increments and logs the value of count. The outer function then returns the inner function. When we call outer(), it returns the inner function which we assign to a variable closureFunction. When we call closureFunction(), it logs and increments the value of count.

Spongebob Meme on understanding closures

Closures are a powerful feature that can help us write more robust and organized code. By utilizing closures, it is possible to generate private variables and functions, which can help avoid unintended modifications to shared state.

Top comments (0)