Understanding JavaScript closures: variables, functions, and scope.

akindeleemmanuel

Akindele Emmanuel

Posted on November 3, 2024

Understanding JavaScript closures: variables, functions, and scope.

“Javascript closures are a fundamental concept in programming, enabling functions to access and manipulate variables from surrounding scopes. This powerful technique allows for data encapsulation, context preservation, and efficient memory management. Understanding Javascript closures is crucial for developing robust, scalable, and maintainable applications. In this article, we will look into the complexity of this concept, exploring variables, functions, and scope to master this essential Javascript concept.”.
Now let's see what a closure in Javascript is. I will like to define this in three ways: in a simple and concise way, in a technical and detailed definition, and in a conceptual and analogous definition.

What is closure in JavaScript?

“A closure is a/are channel(s) through which function inside another function have access to its own scope and the scope of its outer function(s), even when the outer function(s) have returned.”.

“A closure can also be referred to as a self-contained function that maintains a reference to its surrounding lexical scope, allowing it to access and manipulate variables from that scope, even when the function is invoked outside its original context.”.

“A closure is like a room with memory. When a function is created inside another function, it inherits the outer function’s scope, much like a room inherits the features of the building it’s in. Even when the outer function ‘closes’ (returns), the inner function remembers the outer scope, allowing it to access its variables and functions". These definitions highlight different aspects of JavaScript closure.

To buttress the definitions or for better understanding of the subject matter, think of a closure like this. Imagine you have a toy box container where you keep all your favorite toys (the toy box container is our outer function). Now imagine that inside the toy container (outerfunction) you have different toys like cars, dolls, and a robot, among other things. (these are variables or any other function) out of these toys, you have a special toy (inner function) which is the robot. Imagine the robot has special powers through a channel; it can play or connect all the other toys inside the toy box even when the toy box is closed. Imagine that special channel or power to be closure. I hope you get that. Let's see an example of a code to illustrate closure.

<script>
        function details() {
            let surName = 'john';
            let lastName = 'mercy';
            function displayDetails() {
                return `hey ${surName} ${lastName} you have been registered`;
            }
            return displayDetails();
        }
        console.log(details());
    </script>
Enter fullscreen mode Exit fullscreen mode

In the code above, the displayDetails is the function or the closure, or better still, referring to the illustration before the code. funtion displayDetails is using the power of closure to access the variables outside it’s scope. Here is the thing. displayDetails is defined inside details, it accesses surName and lastName from the outer scope, and it retains this access even outside its scope. Or, in another way, details create a scope with surName and lastName, displayDetails access this scope, displayDetail returns a string using surName and lastName, and details returns displayDetails’s result. console.log(details()); calls displayDetails, accessing outer scope variables.
The output of this code is hey john mercy, you have been registered
The result is shown below

the image display the output of the to explain what a closure is

Now that you understand closure, let's see the benefit of closure in Javascript code writing.

Variables in closures

  • Local variables: Variables declared within function, is accessible only within the function scope and not accessible outside the scope.
  • Outer variables: Variables declared in an outer function are accessible to inner function
  • Global Variables: Variables declared outside all functions, accessible from anywhere

Functions in closure

  • Inner functions: these are functions defined within another function that have access to outer scope
  • Outer function: this function defines the scope for inner functions
  • Function expressions: function defined as expressions can be used as closures

Scope in closures

  • Lexical scoping: inner functions have access to outer scope.
  • Dynamic scoping: scope is determined at runtime ( not used in javascript).

What are the benefits of closure?

  • Data hiding: protecting data from external access Let’s see in the code below example of code that exhibits this data hiding
<script>
        function Person(name, age) {
            let privateName =  name;
            let privateAge = age;

            return {
                getName:function() {
                    return privateName;
                },
                getAge:function() {
                    return privateAge;
                },
                setAge:function(newAge) {
                    privateAge= newAge;
                }
            };
        }
        const person = Person('bala daodu', 30);
        console.log(person.getName());
        console.log(person.getAge());
    </script>
Enter fullscreen mode Exit fullscreen mode

In the code above, the function Person takes two arguments: name and age, This function creates a new person object. Inside the function, two private variables are declared: privateName and privateAge. These variables are assigned the values passed to the person function ( name and Age). These variables are private because they’re declared with let and aren’t directly accessible outside the Person function. The return objects are also created with three methods. These three methods provide controlled access to private variables. So the Person function creates a closure, allowing the returned object to access private variables. Also the private variables are hidden from external access, providing data protection.

  • Encapsulations: bundling data and methods
  • Context preservation: retaining context in asynchronous calls.

Common use cases of closure

  • Event listeners or event handling: preserving event context. Here is a simple event handling code

<body>
    <button id="myButton">Click me!</button>
    <p id="clickcounter"></p>
    <script>
        const button = document.getElementById('myButton');
        const clickCounterElement=document.getElementById('clickcounter')
        let clickcounter = 0;
        button.addEventListener('click',
            function (){
                clickcounter++;

                clickCounterElement.textContent=(`you have clicked ${clickcounter} times`);
            }
        );      
    </script>
</body>

Enter fullscreen mode Exit fullscreen mode

Here is what happened in the code. We define a function createClickCounter that returns another function. Inside createClickCounter, we declare a variable clickCounter initialized to 0.
The returned function increments clickCounter and updates the text content of clickCounterElement. We call createClickCounter() to create a closure and assign it to the counter variable. We attach the counter function to the button's click event using addEventListener.

The counter function is a closure because it has access to its own scope, has access to the outer function's scope (createClickCounter()), retains the state of clickCounter between function calls.

  • Callback functions: preserving context in asynchronous calls.
  • Private modules: creating private variables and functions

Conclusion

JavaScript closures empower developers to write efficient, modular, and secure code. By mastering variables, functions, and scope, developers can harness closures full potential. Closures enable data encapsulation, state preservation, and private variables, elevating code quality and maintainability. With this foundational understanding, developers can tackle complex Javascript challenges with confidence. Effective use of closures is essential for scalable, robust, and efficient JavaScript applications.

💖 💪 🙅 🚩
akindeleemmanuel
Akindele Emmanuel

Posted on November 3, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related