

{"id":67959,"date":"2019-08-16T14:53:48","date_gmt":"2019-08-16T09:23:48","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=67959"},"modified":"2019-08-16T15:22:07","modified_gmt":"2019-08-16T09:52:07","slug":"javascript-closures","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/javascript-closures\/","title":{"rendered":"JavaScript Closures &#8211; The only concept to define Private Data in JavaScript"},"content":{"rendered":"<div class='__iawmlf-post-loop-links' style='display:none;' data-iawmlf-post-links='[{&quot;id&quot;:1446,&quot;href&quot;:&quot;https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Iteration&quot;,&quot;archived_href&quot;:&quot;http:\\\/\\\/web-wp.archive.org\\\/web\\\/20251006105231\\\/https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Iteration&quot;,&quot;redirect_href&quot;:&quot;&quot;,&quot;checks&quot;:[{&quot;date&quot;:&quot;2025-12-09 07:14:10&quot;,&quot;http_code&quot;:200}],&quot;broken&quot;:false,&quot;last_checked&quot;:{&quot;date&quot;:&quot;2025-12-09 07:14:10&quot;,&quot;http_code&quot;:200},&quot;process&quot;:&quot;done&quot;}]'><\/div>\n<p><span style=\"font-weight: 400\">JavaScript provides us with a lot of freedom in terms of functions. We can dynamically create a function, copy it to another variable, call it from a different place in your program or pass it as a parameter to another function. We can access variables defined inside (local variables) as well as outside the function. But <em>what happens when the value of the variable changes during execution?<\/em> Or<em> if multiple functions access the same variable and one of them changes the value?<\/em> Our code will be in shambles, and this will lead to unwanted results. <em>How to solve this?<\/em> The answer to that question is<strong> JavaScript Closures<\/strong>. You don&#8217;t have to know JavaScript closures as a beginner. But, if you wish to get an in-depth understanding of how JavaScript works, this topic is crucial for you. Understanding the working of any programming language is better than learning the syntax. It gives you better tools when you encounter an error or when you want to perform debugging.<\/span><\/p>\n<p><em><strong>Before moving further, please complete the <a href=\"https:\/\/data-flair.training\/blogs\/javascript-regular-expression\/\">JavaScript Regular Expression Tutorial<\/a><\/strong><\/em><\/p>\n<h3><span style=\"font-weight: 400\">The Lexical Environment in JavaScript<\/span><\/h3>\n<p><span style=\"font-weight: 400\">Every time you create a scope in your program with the help of the curly braces { }, you create an internal (hidden) associated object called a lexical environment. It can be defined with a running function, code block, or an entire script. It is a logistical concept, and there is no way to access it from your JavaScript code. There are two components of a lexical environment:<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\"><strong>Environment Record &#8211;<\/strong>\u00a0This is the object that stores all the local variables as its property.<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">A <strong>reference to the outer lexical environment<\/strong> (binds the outer code).<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400\">You need to remember that when the code wants to access a variable, it starts from the inner lexical environment (inner scope of the local variables), then moves outwards to the outer lexical environment. It finishes its search after it goes through the global lexical environment.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Problems with Function Scope<\/span><\/h3>\n<p><span style=\"font-weight: 400\">Many a time, it happens that we modify the value of a variable in our program during execution. Also, some functions use the same variables. So the question that arises here is this: <em>When we change the variable value, does the value in the function changes too?<\/em> Let\u2019s find out with the help of some simple codes that present us with different situations.<\/span><\/p>\n<p><strong>Situation 1: When we use a global variable in the function.<\/strong><\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;html&gt;\r\n    &lt;body&gt;\r\n\r\n        &lt;script&gt;\r\n            let count = 0; \/\/ global variable declared\r\n            function sayHello(){\r\n                count++; \/\/increments the value of the global variable\r\n            }\r\n            sayHello();\r\n            document.write(\"Hello DataFlair.&lt;\/br&gt; Counter: \" + count + \"&lt;\/br&gt;\");\r\n            count = 7; \/\/ global variable redeclared\r\n            sayHello(); \/\/ uses redeclared variable name\r\n            sayHello();\r\n            document.write(\"Counter: \" + count + \"&lt;\/br&gt;\");\r\n        &lt;\/script&gt;\r\n\r\n    &lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p><strong>Screenshot:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-68015\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function.jpg\" alt=\"using global variable in function - JavaScript Closures\" width=\"1299\" height=\"742\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function.jpg 1299w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-768x439.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-1024x585.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-520x297.jpg 520w\" sizes=\"auto, (max-width: 1299px) 100vw, 1299px\" \/><\/a><\/p>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-output-1.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"img-gray-border aligncenter wp-image-68032 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-output-1.jpg\" alt=\"using global variable in function output\" width=\"1298\" height=\"742\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-output-1.jpg 1298w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-output-1-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-output-1-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-output-1-768x439.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-output-1-1024x585.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-global-variable-in-function-output-1-520x297.jpg 520w\" sizes=\"auto, (max-width: 1298px) 100vw, 1298px\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400\">Oops! Something went wrong, didn\u2019t it? We wanted to count how many times we called the function <strong>sayHello()<\/strong> using a global variable that stores its value. Instead, the last line in our output suggests that we accidentally incremented the redeclared variable of the global variable. Let\u2019s try again. But this time, we\u2019ll use a local variable to do that for me.<\/span><\/p>\n<p><strong>Situation 2: When we use a local variable in the function.<\/strong><\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;html&gt;\r\n      &lt;body&gt;\r\n\r\n          &lt;script&gt;\r\n                  document.write(\"Using local variables:&lt;\/br&gt;\")\r\n                  function Counter(){\r\n                      let count = 0; \/\/ local variable declared\r\n                      count++; \/\/ increments the value of the variable\r\n                      return function(){\r\n                              document.write(\"Counter: \" + count + \"&lt;\/br&gt;\");\r\n\r\n                      }\r\n\r\n                  }\r\n\r\n                  var myFunction = Counter();\r\n                  myFunction();\r\n                  myFunction();\r\n                  myFunction();\r\n          &lt;\/script&gt;\r\n\r\n      &lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p><strong>Screenshot:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-68026\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function.jpg\" alt=\"using local variable in function code\" width=\"1298\" height=\"741\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function.jpg 1298w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-768x438.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-1024x585.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-520x297.jpg 520w\" sizes=\"auto, (max-width: 1298px) 100vw, 1298px\" \/><\/a><\/p>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-output.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"img-gray-border aligncenter wp-image-68030 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-output.jpg\" alt=\"using local variable in function output\" width=\"1300\" height=\"742\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-output.jpg 1300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-output-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-output-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-output-768x438.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-output-1024x584.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/using-local-variable-in-function-output-520x297.jpg 520w\" sizes=\"auto, (max-width: 1300px) 100vw, 1300px\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400\">Okay, that really wasn\u2019t the output I wanted. What happened? Well, we used the local variable in our function, which resets every time a function returns. Thus after each function call, the <\/span><b>count<\/b><span style=\"font-weight: 400\"> returns to zero.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The problem with the above functions was that we misinterpreted the function scope. What we need to understand is that during a function invocation, the script creates a new scope for that call. Thus, we need to remember that the function scope is for a function call, rather than the function itself.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Well, these two approaches failed, big way. But wait, don\u2019t be disappointed, JavaScript has something for you to solve this problem just right: <strong>Closures<\/strong>.<\/span><\/p>\n<p><em><strong>Wait a minute! Have you learned about <a href=\"https:\/\/data-flair.training\/blogs\/javascript-variable-tutorial\/\">JavaScript Variable Declaration<\/a><\/strong><\/em><\/p>\n<h2><span style=\"font-weight: 400\">What are JavaScript Closures?<\/span><\/h2>\n<p><span style=\"font-weight: 400\">In the above problem, we need to create \u2018private\u2019 variables for a function in a way that they don\u2019t reset after the function returns. We can achieve the desired output with the help of closures<em>. A closure is a combination of a function and the lexical environment where we declared the variable.<\/em> It can access the parent scope even after the parent function closes. This environment contains any local variables that were in-scope at the time of closure creation. You might be wondering how that is possible, right?<\/span><\/p>\n<p><span style=\"font-weight: 400\">Closures make use of self-invoking functions in JavaScript. Since these functions run only once, they set the values of the variables and then returns a function expression. The important fact is that they are \u201cnested functions\u201d, thus they can access the outer variables (variables in the parent scope). Let\u2019s understand this approach with the help of an example.<\/span><\/p>\n<p><strong>Situation 3: When we use a closure.<\/strong><\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;html&gt;\r\n    &lt;body&gt;\r\n\r\n        &lt;script&gt;\r\n            document.write(\"DataFlair: Using Closures&lt;\/br&gt;\")\r\n            function Counter(){\r\n                let count = 0; \/\/ local variable declared\r\n\r\n                return function(){\r\n                        count++; \/\/increments the value of the variable\r\n                        document.write(\"Counter: \" + count + \"&lt;\/br&gt;\");\r\n                }\r\n\r\n            }\r\n            var myFunction = Counter();\r\n            myFunction();\r\n            myFunction();\r\n            myFunction();\r\n\r\n        &lt;\/script&gt;\r\n\r\n    &lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p><strong>Screenshot:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-68018\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code.jpg\" alt=\"Using JavaScript Closures Code\" width=\"1299\" height=\"742\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code.jpg 1299w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-768x439.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-1024x585.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-520x297.jpg 520w\" sizes=\"auto, (max-width: 1299px) 100vw, 1299px\" \/><\/a><\/p>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"img-gray-border aligncenter wp-image-68019 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output.jpg\" alt=\"Using JavaScript Closures Output\" width=\"1300\" height=\"742\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output.jpg 1300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-768x438.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-1024x584.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-520x297.jpg 520w\" sizes=\"auto, (max-width: 1300px) 100vw, 1300px\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400\">In this example, the <\/span><b>count<\/b><span style=\"font-weight: 400\"> is protected by the scope of the anonymous, and we can only alter it while using the<strong> Counter()<\/strong> function. The program below makes the working of a closure a little more clear.<\/span><\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;html&gt;\r\n    &lt;body&gt;\r\n\r\n        &lt;script&gt;\r\n            function addNumbers(num1){ \/\/closure\r\n                return function(num2){\r\n                    return num1 + num2;\r\n                };\r\n            }\r\n            \/\/ calling the outer function for num1\r\n            var add20 = addNumbers(20);\r\n            var add30 = addNumbers(30);\r\n            \/\/ calling the inner function for num2\r\n            document.write(\"Sum1:&lt;\/br&gt;20 + 30 = \" + add20(30) + \"&lt;\/br&gt;\");\r\n\r\n            document.write(\"Sum2:&lt;\/br&gt;30 + 70 =\u00a0 \" + add30(70) + \"&lt;\/br&gt;\");\r\n        &lt;\/script&gt;\r\n\r\n    &lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p><strong>Screenshot:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-2.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-68022\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-2.jpg\" alt=\"Using JavaScript Closures Code 2\" width=\"1298\" height=\"744\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-2.jpg 1298w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-2-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-2-300x172.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-2-768x440.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-2-1024x587.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Code-2-520x298.jpg 520w\" sizes=\"auto, (max-width: 1298px) 100vw, 1298px\" \/><\/a><\/p>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-2.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"img-gray-border aligncenter wp-image-68024 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-2.jpg\" alt=\"Using JavaScript Closures Output 2\" width=\"1299\" height=\"741\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-2.jpg 1299w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-2-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-2-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-2-768x438.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-2-1024x584.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/Using-JavaScript-Closures-Output-2-520x297.jpg 520w\" sizes=\"auto, (max-width: 1299px) 100vw, 1299px\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400\">Notice that the parent function for add20 and add30 returned before we accessed the inner functions. It is because both of them are closures, saving the parent properties. Thus, we got the exact output we wanted. Try doing that with the help of a regular function and compare the two outputs.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Determining whether a given Function is Closure or not<\/span><\/h3>\n<p><span style=\"font-weight: 400\">Alright, we learned how to define a closure in our program. Now, we will find out <em>whether\u00a0a given function is a closure or not? Is there any way you can differentiate them from a normal function?<\/em> <strong>Yes, there is.<\/strong> You can do that by noticing the inner function. <em>Can you access the inner function directly? Do you have the means to call the nested function without its parent function?<\/em> If the <strong>answer is no,<\/strong> then my friend, you\u2019ve<strong> got a JavaScript closure.<\/strong><\/span><\/p>\n<p><span style=\"font-weight: 400\">It is because, in a closure, you can access an inner function only with the help of its parent function. It prevents an unauthorized user from accessing all the properties of the closure. In other programming languages like Java, we use access modifiers to define private properties in a class. Since we don\u2019t have such a keyword available in JavaScript, we use closures.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Remember, you will often see that the inner function is anonymous. The reason is that it works as a wrapper around the code you want to protect from outer access.<\/span><\/p>\n<p><em><strong>Time to revise the <a href=\"https:\/\/data-flair.training\/blogs\/javascript-function\/\">different types of JavaScript Functions<\/a><\/strong><\/em><\/p>\n<h3><span style=\"font-weight: 400\">Why are JavaScript Closures so important?<\/span><\/h3>\n<p><span style=\"font-weight: 400\">Closures are very useful when you want to define private properties in JavaScript. Some programmers prefix private properties with an underscore (_), indicating that you should not modify that property. But this does nothing to implement information hiding, rather gives the warning to be careful while using these values. On the other hand, closures are like a welcome mat between the outer scope and the rest of the program. They are magical since they allow us to achieve private data in JavaScript.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">The problem in\u00a0<\/span><span style=\"font-weight: 400\">JavaScript Closure Loop\u00a0<\/span><\/h3>\n<p><span style=\"font-weight: 400\">Before the introduction of ECMAScript 2015, there was a common problem while using closures with loops. The problem is clear from the code below.<\/span><\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;html&gt;\r\n    &lt;body&gt;\r\n        &lt;script type=\"text\/javascript\"&gt;\r\n                var variables = []; \/\/creating an empty array\r\n                for (var iterator = 0; iterator &lt; 3; iterator++) {\r\n                    \/\/adding values to the array (closure)\r\n\u00a0 \u00a0 variables[iterator] = function() {\r\n\u00a0 \u00a0     console.log(\"My value: \" + iterator);\r\n\u00a0 \u00a0 };\r\n  }\r\n  \/\/iterating through each value in the array\r\n  for (var iterator2 = 0; iterator2 &lt; 3; iterator2++) {\r\n\u00a0     variables[iterator2]();\r\n  }\r\n        &lt;\/script&gt;\r\n    &lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p><strong>Screenshot:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-68044\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem.jpg\" alt=\"closure loop problem \" width=\"1298\" height=\"742\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem.jpg 1298w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-768x439.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-1024x585.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-520x297.jpg 520w\" sizes=\"auto, (max-width: 1298px) 100vw, 1298px\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400\">We expected the value as follows:<\/span><\/p>\n<p><span style=\"font-weight: 400\">My value: 0<\/span><\/p>\n<p><span style=\"font-weight: 400\">My value: 1<\/span><\/p>\n<p><span style=\"font-weight: 400\">My value: 2<\/span><\/p>\n<p><span style=\"font-weight: 400\">The <strong>output<\/strong> we get is, as shown below:<\/span><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-output.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"img-gray-border aligncenter wp-image-68045 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-output.jpg\" alt=\"closure loop problem output\" width=\"1298\" height=\"742\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-output.jpg 1298w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-output-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-output-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-output-768x439.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-output-1024x585.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-output-520x297.jpg 520w\" sizes=\"auto, (max-width: 1298px) 100vw, 1298px\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400\">Unexpected, wasn\u2019t it? The problem lies with the variable declaration. There are two ways you can solve this problem. First, you can change the name of the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Iteration\">iteration<\/a> variable of the second loop so that it doesn\u2019t always run with the value 3 (set by the previous <\/span><i><span style=\"font-weight: 400\">for<\/span><\/i><span style=\"font-weight: 400\"> loop). Another approach you can use in modern browsers is the use of \u2018let\u2019 keyword for variable declaration. It prevents the continuous changing of the variable\u2019s value and gets the desired output.<\/span><\/p>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-solution-output.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"img-gray-border aligncenter wp-image-68046 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-solution-output.jpg\" alt=\"closure loop problem solution output\" width=\"1300\" height=\"742\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-solution-output.jpg 1300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-solution-output-150x86.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-solution-output-300x171.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-solution-output-768x438.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-solution-output-1024x584.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/closure-loop-problem-solution-output-520x297.jpg 520w\" sizes=\"auto, (max-width: 1300px) 100vw, 1300px\" \/><\/a><\/p>\n<p><em><strong>Do you know about <a href=\"https:\/\/data-flair.training\/blogs\/javascript-loop-control\/\">JavaScript Loop Control Statements<\/a><\/strong><\/em><\/p>\n<p><span style=\"font-weight: 400\">Much better now, and just what we wanted the output to be. Experiment with this code and other codes where you use closures inside a function. You need to practice numerous problems to master the concept. If you get stuck, come back to the JavaScript closures tutorial and try to find out the problem when you get stuck.\u00a0<\/span><\/p>\n<h2><span style=\"font-weight: 400\">Summary<\/span><\/h2>\n<p><span style=\"font-weight: 400\">In this tutorial, we learned a lot about\u00a0JavaScript closures. We discussed the various problems with a normal function and how JavaScript closures help in that case. We also reviewed why we need closures in our JavaScript program.<\/span><\/p>\n<p><em><strong>Thinking, what to learn next? Here is the <a href=\"https:\/\/data-flair.training\/blogs\/javascript-garbage-collection\/\">JavaScript Garbage Collection Tutorial<\/a> for you.<\/strong><\/em><\/p>\n<p>Feedbacks and suggestions for us? Mention them in the comment section of JavaScript Closures Tutorial. We will be glad to hear from you. Keep visiting DataFlair for regular updates.<\/p>\n<p><strong>Happy Learning!<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>JavaScript provides us with a lot of freedom in terms of functions. We can dynamically create a function, copy it to another variable, call it from a different place in your program or pass&#46;&#46;&#46;<\/p>\n","protected":false},"author":7,"featured_media":68033,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18979],"tags":[20880,20873,20879,20878],"class_list":["post-67959","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","tag-javascript-closure-loop-problem","tag-javascript-closures","tag-javascript-closures-importance","tag-javascript-lexical-environment"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>JavaScript Closures - The only concept to define Private Data in JavaScript - DataFlair<\/title>\n<meta name=\"description\" content=\"Learn about JavaScript lexical environment, problems with function scope then implement closures in JavaScript &amp; explore its importance &amp; problem in JavaScript closure loop.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/javascript-closures\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JavaScript Closures - The only concept to define Private Data in JavaScript - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Learn about JavaScript lexical environment, problems with function scope then implement closures in JavaScript &amp; explore its importance &amp; problem in JavaScript closure loop.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/javascript-closures\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2019-08-16T09:23:48+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-08-16T09:52:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/JavaScript-Closures-Tutorial.png\" \/>\n\t<meta property=\"og:image:width\" content=\"801\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"JavaScript Closures - The only concept to define Private Data in JavaScript - DataFlair","description":"Learn about JavaScript lexical environment, problems with function scope then implement closures in JavaScript & explore its importance & problem in JavaScript closure loop.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/javascript-closures\/","og_locale":"en_US","og_type":"article","og_title":"JavaScript Closures - The only concept to define Private Data in JavaScript - DataFlair","og_description":"Learn about JavaScript lexical environment, problems with function scope then implement closures in JavaScript & explore its importance & problem in JavaScript closure loop.","og_url":"https:\/\/data-flair.training\/blogs\/javascript-closures\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2019-08-16T09:23:48+00:00","article_modified_time":"2019-08-16T09:52:07+00:00","og_image":[{"width":801,"height":420,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/JavaScript-Closures-Tutorial.png","type":"image\/png"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/beb0cab24b7aa54423a3b50e669a9dcd"},"headline":"JavaScript Closures &#8211; The only concept to define Private Data in JavaScript","datePublished":"2019-08-16T09:23:48+00:00","dateModified":"2019-08-16T09:52:07+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/"},"wordCount":1434,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/JavaScript-Closures-Tutorial.png","keywords":["JavaScript Closure Loop\u00a0Problem","JavaScript Closures","JavaScript Closures Importance","JavaScript Lexical Environment"],"articleSection":["JavaScript Tutorial"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/javascript-closures\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/","url":"https:\/\/data-flair.training\/blogs\/javascript-closures\/","name":"JavaScript Closures - The only concept to define Private Data in JavaScript - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/JavaScript-Closures-Tutorial.png","datePublished":"2019-08-16T09:23:48+00:00","dateModified":"2019-08-16T09:52:07+00:00","description":"Learn about JavaScript lexical environment, problems with function scope then implement closures in JavaScript & explore its importance & problem in JavaScript closure loop.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/javascript-closures\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/JavaScript-Closures-Tutorial.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/08\/JavaScript-Closures-Tutorial.png","width":801,"height":420,"caption":"JavaScript Closures Tutorial"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/javascript-closures\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"JavaScript Tutorial","item":"https:\/\/data-flair.training\/blogs\/category\/javascript\/"},{"@type":"ListItem","position":3,"name":"JavaScript Closures &#8211; The only concept to define Private Data in JavaScript"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/beb0cab24b7aa54423a3b50e669a9dcd","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c322416204232f4dd97ef3901b0a499a5d34d7ba7fe333f4bfe53a907873d293?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c322416204232f4dd97ef3901b0a499a5d34d7ba7fe333f4bfe53a907873d293?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c322416204232f4dd97ef3901b0a499a5d34d7ba7fe333f4bfe53a907873d293?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team specializes in creating clear, actionable content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Backed by industry expertise, we make learning easy and career-oriented for beginners and pros alike.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam3\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/67959","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=67959"}],"version-history":[{"count":9,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/67959\/revisions"}],"predecessor-version":[{"id":68052,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/67959\/revisions\/68052"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/68033"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=67959"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=67959"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=67959"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}