Skip to content
Related Articles

Related Articles

Data Privacy Using Closures in JavaScript

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 28 Apr, 2022

Let’s first understand what closures are in Javascript.

Closures: A function along with a reference to the outer environment together forms a closure. In other words, we can say that it’s a combination of a function and its lexical scope bundled together which means the inner function has access to its outer lexical environment i.e. access to the variables of the parent function together forms a closure.

Example:

Javascript




<script>
function x() {
    var a = "GeeksforGeeks";
    function y() {
        console.log(a);
    }
    return y;
}
x()();
</script>


Output:

Before discussing data privacy, let’s understand encapsulation and data hiding.

Data hiding is like we have a variable and we want privacy over it so that no other functions or other parts of the code can have access over it is called Data hiding or data privacy. In other words, we are just encapsulating the data so that other parts of the code can’t have access to it.

Let’s Understand with the help of an example: Here we have a counter variable that we can access from the outside of the increase function from in part of the code.

Javascript




<script>
    var counter = 0;
  
    function increase() {
        counter++;
        console.log("Access of counter from inside "
            + "the function as it forms a closure"
            counter);
    }
  
    increase();
      
    // No data Privacy
    console.log("Accessed from outside also no "
        + "data privacy", counter);
</script>


Output:

So on the above part, we can see that data is not hidden or no data privacy.

Now let’s apply the concept of closures. We will wrap the increase function with a function. So that the increase function will have access over its lexical environment only.

Javascript




<script>
    function count() {
        var counter = 0;
        function increase() {
            counter++;
            console.log("Access of counter from "
                + "inside the function as it forms"
                + " a closure", counter);
        }
        return increase;
    }
  
    count()();
      
    // Data Privacy is there is
    // it will throw error
    console.log("Accessed from outside also no"
        + " data privacy", counter);
</script>


Output:

Here now after wrapping the increase function under a function, we can maintain data privacy and we can not call counter outside the function. This is all due to closures. It played the main role by limiting the access of counter within the lexical environment of the increase function .


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!