DEV Community

Ayako yk
Ayako yk

Posted on • Edited on

3

JavaScript Closure

While working with a React Hook, I came across closures. Although I had read about them in a document, I found it difficult to apply them to actual code. This article provides a summary of closures.

  1. JavaScript functions and scopes
  2. Closure with example codes

JavaScript functions and scopes
A JavaScript function allows the inner function to access the variable in its outer scope.

When a variable is declared outside of a function or as a global variable, assigning a new value to the variable changes its value.
It can affect the behavior of the program in ways that may be unexpected or undesirable.

let x = 10;

function myFunction(){
    return x + x;
}

myFunction() // 20

x = 20;

myFunction() // 40
Enter fullscreen mode Exit fullscreen mode

When a variable is declared inside a function with an initial value, it sets to the initial value every time the function is called.

function outerFunction(){
    let count = 10;
    console.log("initialized", count)

    function innerFunction(){
        count -= 1;
        console.log("decremented", count)
        return count;
    }

    innerFunction()
}

outerFunction() // initialized 10, decremented 9
outerFunction() // initialized 10, decremented 9
outerFunction() // initialized 10, decremented 9
Enter fullscreen mode Exit fullscreen mode

Here comes the Closures.

Closures

According to 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.

When calling the outer function, the outer function references its inner function.
The outer variables can keep their states between multiple calls.

function countdown(){
    let count = 10;

    function decrement(){
        return count -= 1;
    }

    return decrement;
}

let counter = countdown();

counter() // 9
counter() // 8
counter() // 7
Enter fullscreen mode Exit fullscreen mode

Why do we store the function in a global variable?
To store the result of the variable and its inner function, which allows the outer variable to maintain its state even after the function has been called multiple times.

We can create a new, separate counter, "counter2" by calling countdown() again. This counter has its own count variable.

function countdown(){
    let count = 10;

    function decrement(){
        return count -= 1;
    }

    return decrement;
}

let counter = countdown();

counter() // 9
counter() // 8
counter() // 7

let counter2 = countdown();
counter2() // 9
counter2() // 8
counter2() // 7
Enter fullscreen mode Exit fullscreen mode

This blog post provides a simplified summary of JavaScript functions and scopes, focusing on the concept of closures. Closures allow inner functions to access variables in their outer scope and retain state information between multiple calls.

If you're struggling with closures or have encountered problems related to function scopes, I hope this summary helps you understand the basics and get unstuck.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay