{"id":1358,"date":"2016-01-30T14:14:47","date_gmt":"2016-01-30T14:14:47","guid":{"rendered":"http:\/\/frowningbear.com\/codebase\/?p=1358"},"modified":"2019-01-30T14:19:06","modified_gmt":"2019-01-30T14:19:06","slug":"closures-continued","status":"publish","type":"post","link":"https:\/\/frowningbear.com\/codebase\/2016\/01\/30\/closures-continued\/","title":{"rendered":"Closures continued"},"content":{"rendered":"\n<p><a href=\"http:\/\/frowningbear.com\/codebase\/index.php\/2016\/01\/20\/returning-in-javascript-and-intoduction-to-closures\/\">Previously<\/a> I gave a brief introduction to closures in Javascript. Here I will attempt to provide more understanding on this topic. I will lead into the topic of closures by beginning with a look at an infamous problem with for loops in Javascript. I will also briefly touch on <b>Immediately Invoked Function Expressions (IIFEs)<\/b>.<\/p>\n\n\n\n<p><!--more--><\/p>\n\n\n\n<p>Consider the following code snippet.<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">var arrayOfFunctions = [];\n\nfunction buildFunctions() {\n\n    for (var i = 0; i &lt; 3; i++) {\n        arrayOfFunctions.push(function(){\n            console.log(i); \n        \n        });\n    }\n\n    return arrayOfFunctions;\n}\n\n\/\/ fs will now be an array that contains a function as each of its items\nvar fs = buildFunctions();\n\n\/\/ fs[0] will refer to the first array item and fs[0]() will call that first item because, being a function, it is callable.\n\nfs[0]();\n\nfs[1]();\n\nfs[2]();<\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li>The <code>buildFunctions()<\/code> function will add an item to the end of the array. In this case, the item added will be a function. <\/li><li>The definition for the function specifies to log what ever the value of <code>i<\/code>  is when you run the function later on, not what the current value of <code>i<\/code>  is at the time the loop is running. <\/li><\/ul>\n\n\n\n<p>In the first iteration of the loop, when we come across the following&#8230;<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">arrayOfFunctions.push(function() {\n\tconsole.log(i); \n});<\/pre>\n\n\n\n<p>Here we are adding a function to the array which will log the value of <code>i<\/code>, and because the value of <code>i<\/code> is currently 0 at that point (then 1, then 2 etc), we might think we are telling the function to log the value of 0, but we are actually telling it to log the value of <code>i<\/code>, whatever that value will be at some point in the future, not what it currently is right now as the loop is running. It not only sounds confusing but LOOKS confusing.<\/p>\n\n\n\n<p>Look at this simpler example.<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">for (var i = 0; i &lt; 3; i++) {\n  console.log(i); \/\/ log what i currently is, at this point in the loop, right now\n} \n\n\/* logs:\n0\n1\n2\n*\/<\/pre>\n\n\n\n<p>Now compare it with the following.<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">for (var i = 0; i &lt; 3; i++) {\n  alert(i); \n} \nconsole.log(i); \/\/ logs 3<\/pre>\n\n\n\n<p>Here we have moved the log statement out of the loop and just replaced it with an alert.<br> The alert will display 1, 2, 3 respectively, but what will the log statement show?<br> It will show 3 because by this stage the loop has finished running and the <b>final<\/b> value of <code>i<\/code> will be equal to 3.<\/p>\n\n\n\n<p>Looking back at our original code&#8230;<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">arrayOfFunctions.push(function() {\n\tconsole.log(i); \/\/ console.log statement doesn't run now but later  \n});<\/pre>\n\n\n\n<p>The <code>console.log<\/code> function does not run at that time, in other words, it does not run during the execution of the for loop, so it does not matter what the current value of <code>i<\/code> is at that point in the loop because the log function is not being run then. When the log function is finally run later (by calling its containing function as an item of the array) it will log whatever <code>i<\/code> happens to be then, which in our example will be 3, because by then the loop has finished running.<\/p>\n\n\n\n<p>So how do we get the functions to log the different index numbers? The solution is to use a closure.<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">var arrayOfFunctions = [];\n\nfunction buildFunctions() {\n\n    for (var i = 0; i &lt; 3; i++) {\n\n        arrayOfFunctions.push(\n\n            (function(currentValueOfI) { \n        \t    return function(){\n                    console.log(currentValueOfI);\n                }\n            }(i)) \/\/ end of IIFE        \n        \n        ) \/\/ end of push statement\n    } \/\/ end of for loop\n\n    return arrayOfFunctions;\n}<\/pre>\n\n\n\n<p>On each iteration of the loop we add an item to the array, as we did before. The item that is added will be the result of running the IIFE. The IIFE returns a function, so the item added to the array will obviously be a function. In the first iteration the value of <code>i<\/code> is equal to 0. The IIFE will call itself with <code>i<\/code> (0) as its argument. That value will be supplied to the parameter\/placeholder <code>currentValueOfI<\/code>.<\/p>\n\n\n\n<p>The IIFE returns a function that will later log that argument which was supplied (in this case, 0). So when we later call <code>arrayOfFunctions[0]()<\/code>, it will &#8220;remember&#8221; that at the time we defined that function as an array item, the value of <code>i<\/code> was equal to 0, because we captured it in another variable called <code>currentValueOfI<\/code>.<\/p>\n\n\n\n<p>On the second iteration the value of i (now equal to 1) will be once again captured in another variable called <code>currentValueOfI<\/code>.<\/p>\n\n\n\n<p>But won&#8217;t that clash with, or overwrite, the previous variable called <code>currentValueOfI<\/code> which was set to 0?<\/p>\n\n\n\n<p>No, because each time the loop iterates, it runs the same IIFE, but each execution of that IIFE creates its own <b>execution context<\/b> (its own scope, in other words), so there will be more than one variable called <code>currentValueOfI<\/code> but they will be separately contained in their own scope\/execution context. <\/p>\n\n\n\n<p>Look at the following alteration of our original example and read the comments closely.<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ create a global variable called j\nvar j = 25; \n\nvar arrayOfFunctions = [];\n\nfunction buildFunctions() {\n\n    for (var i = 0; i &lt; 3; i++) {\n        arrayOfFunctions.push(function(){\n        \t\/\/ log j instead of i. Shows that the current value of i in the loop is irrelevant to the function we are adding to the array. It couldn't care less.\n            console.log(j); \n        \n        });\n    }\n\n    return arrayOfFunctions;\n}\n\nvar fs = buildFunctions();\n\nfs[0](); \/\/ logs 25\n\nfs[1](); \/\/ logs 25\n\n\/\/ modify (update) j\nj = 50;\n\n\/\/ only cares what current value of j is\nfs[2](); \/\/ logs 50<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Previously I gave a brief introduction to closures in Javascript. Here I will attempt to provide more understanding on this topic. I will lead into the topic of closures by beginning with a look at an infamous problem with for loops in Javascript. I will also briefly touch on Immediately Invoked Function Expressions (IIFEs).<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[3],"tags":[53,55,56],"class_list":["post-1358","post","type-post","status-publish","format-standard","hentry","category-javascript","tag-closure","tag-function","tag-iife"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/1358","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/comments?post=1358"}],"version-history":[{"count":2,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/1358\/revisions"}],"predecessor-version":[{"id":1361,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/1358\/revisions\/1361"}],"wp:attachment":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/media?parent=1358"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/categories?post=1358"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/tags?post=1358"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}