<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Russell Moore on Medium]]></title>
        <description><![CDATA[Stories by Russell Moore on Medium]]></description>
        <link>https://medium.com/@russellwmoore?source=rss-98c0769fbd32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zwSxuwIARNWH79h4HyU2kw.jpeg</url>
            <title>Stories by Russell Moore on Medium</title>
            <link>https://medium.com/@russellwmoore?source=rss-98c0769fbd32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:36:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@russellwmoore/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Closure in JS — It’s not you, it’s me.]]></title>
            <link>https://medium.com/@russellwmoore/closure-in-js-its-not-you-it-s-me-4291309d787b?source=rss-98c0769fbd32------2</link>
            <guid isPermaLink="false">https://medium.com/p/4291309d787b</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Russell Moore]]></dc:creator>
            <pubDate>Wed, 14 Nov 2018 13:44:17 GMT</pubDate>
            <atom:updated>2019-02-25T00:27:23.999Z</atom:updated>
            <content:encoded><![CDATA[<h3>Closure in JavaScript — It’s not you, it’s me.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*HBXZ_6WeMKPuL9wctB2niQ.jpeg" /></figure><p>Closure is a confusing bit, even after you have some experience in JavaScript. I hope this little meditation on closure might bring you closer to having a clearer understanding of this topic.</p><h3>Part 1 : The Tale of a Function and Parenthesis and a Returned value</h3><p>A function is a piece of code that packages functionality. Think of a notecard with a recipe for making toast (yes, please come with me on this adventure of a toast recipe). The recipe on a notecard doesn’t magically create toast for you — you have to <strong><em>execute</em></strong> the following actions in order.</p><ol><li>Remove bread from package</li><li>Put bread in toaster</li><li>Push button down on toaster</li><li>Wait for toast to pop up, retrieve toast from toaster</li><li>Spread butter on toast. (Only monsters eat *dry* toast)</li></ol><p>In other words, you must <strong><em>invoke</em></strong> your toast recipe. You must <strong><em>call </em></strong>your toast recipe. You must <strong><em>execute </em></strong>your toast recipe. (Invoke, call and execute all mean running a function in JavaScript. I will use all of them going forward) In real life, we humans are the executors of a toast recipe. In JavaScript parentheses are the executors of functional recipes. (I’m going to call parentheses ‘parens’ from now on, cool?). Back to recipes…</p><p>Recipes are just slips of paper with instructions on them, and when you execute their instructions you’ll get the food returned from their instructions. Functions are just like recipe cards. They are just a string of words and symbols that lay silent until they are brought to life (ie, <strong><em>called</em></strong>, <strong><em>executed</em></strong> or <strong><em>invoked</em></strong>) with the power of parens.</p><p>Let’s consider an adding function defintion:</p><pre>function adder(num1, num2) {<br>  return num1 + num2<br>}</pre><p>This adding function takes in 2 numbers, and will return their sum. I’ll sleep better knowing that this function is available in computer memory and that I’ll be able to add any two digits together at the drop of a hat. But until we <strong><em>invoke</em></strong> or <strong><em>call</em></strong> or <strong><em>execute</em></strong> this adder function, it won’t add anything together or return any values to us. An uncalled function is just a recipe card laying on the counter in the kitchen.</p><p>Let’s take our adder function and pass in the numbers 2 and 5. When the adder function runs with the arguments 2 and 5, the adder function will return the number 7. I like to think of a function call as a transformation from its invoked state to its returned state. Check out this code example:</p><pre>function adder(num1, num2) {<br>  return num1 + num2<br>}</pre><pre>adder(2,5) // return 7</pre><p>Sometimes it’s helpful to think of invoked functions as transforming into their returned values. Here is an animation of the same code above. The return value from the function call adder(2, 5) is 7 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*_UdlNTouO2_Zm1bAjInRhA.gif" /></figure><p>This concept of a function call transforming into its return value is something that will be crucial to the understanding of functions as return values. I’ll continue to use animations like this to make this clear going forward.</p><h3>Part 2: Scope</h3><p>Functions can access and use variables that are defined in their <strong><em>lexical scope.</em></strong> Take the following piece of code:</p><pre>const wordsToAnnounce = ‘Will the real Slim Shady please stand up?’</pre><pre>function announcementMaker(string) {<br>  console.log(string + wordsToAnnounce);<br>}</pre><pre>// -------------------------</pre><pre>announcementMaker(‘I have an announcement to make: ‘) // returns ‘I have an announcement to make: Will the real Slim Shady please stand up?’</pre><p>The function call of announcementMaker below the dashed line is able to access the variable wordsToAnnounce because wordsToAnnounce is defined in the lexical scope of announcementMaker (<em>sidebar: the parameter called `string` is also defined in </em>announcementMaker&#39;s <em>lexical scope. All passed arguments are in the lexical scope of their own function.</em>)</p><p>I like to think of lexical scope in Javascript like a two-way mirror. At the site of their definition, functions can access variables inside their bodies and can access variables outside of their bodies (the window side of the two-way mirror) but they can’t see inside other functions bodies (the mirror side of a two-way mirror). In other words, the variable wordsToAnnounce is in the lexical scope of the function announcementMaker, so the function announcementMaker can see and access the value stored in wordsToAnnounce.</p><p>What about when a function can’t access a variable, aka when a function will be looking at the mirror half of a two-way mirror you ask? Great question. Consider this:</p><pre>const allAccess = ‘Variable called allAccess in the global scope’</pre><pre>function greedyFunction() {<br>  const wordsToAnnounce = ‘Will the real Slim Shady please stand up?’<br>}</pre><pre>function announcementMaker() {<br>  console.log(wordsToAnnounce)<br>}</pre><pre>announcementMaker() // reference error</pre><p>In this example the function announcementMaker can see out of the two-way mirror into the global scope and see the variable allAccess and the function greedyFunction. However it can’t see through the curly braces in the definition of greedyFunction to access the variable wordsToAnnounce. As a result, we’ll never get to ask Will the real Slim Shady please stand up?</p><h3>Part 3: Functions are…variables?</h3><p>A notable characteristic about JavaScript is that it treats functions as first-class citizens. That is, functions can be passed to other functions as arguments and can also be return values from the execution of another function. We’ll explore functions being the return value of another function. Let’s take our adder function one more time:</p><pre>function adder(num1, num2) {<br>  return num1 + num2<br>}</pre><p>The return value from our adder function is the evaluation of . num1 + num2 and we expect this return value to be a number given that both num1 and num2are numbers.</p><p>Now let’s examine a new function. adderWithReturnedFunction also takes two numbers (num1, num2). But instead of returning a <strong><em>number </em></strong>(the evaluation of the sum of two numbers) like our original adder function, it returns a <strong>function</strong> <strong>definition</strong> instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqHKGR5pvY4VIHm51Uy50Q.gif" /></figure><p>It’s important at this point to remember that a function definition is nothing more than a recipe card. It’s just a set of instructions waiting to be invoked. What’s most interesting about the <em>function returned by </em><em>adderWithReturnedFunction</em> is that all of the parameters that we originally defined as wordsToAnnounce, num1, and num2 have now been replaced by the corresponding values that were available in the lexical scope of the <em>function returned by </em><em>adderWithReturnedFunction</em>. These variables are considered ‘closed over’ by the <em>function returned by </em><em>adderWithReturnedFunction</em>. This means that the <em>function returned by </em><em>adderWithReturnedFunction</em> can access these variables at any time in the future.</p><p>For my last trick I’m going to store the <em>function returned by </em><em>adderWithReturnedFunction</em> into a variable so I can use it in the future with access to its closed over variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFXcyXCt2krnosouw8gp6g.gif" /></figure><p>Hopefully these examples provide an additional perspective to the plethora of material available about this slippery topic. Please be sure to check out many other examples to solidify your own understanding. I recommend the following resources:</p><p><a href="https://www.youtube.com/watch?v=UROINgUKSGw">JavaScript: The Hard Parts</a> : A much more in depth view at closure and other JS topics. Highly recommended. Will Sentance has unusually clear technical language and strategies that I think are wonderful.</p><p><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">Master the JavaScript Interview: What is a Closure?</a> : A great article by <a href="https://medium.com/@_ericelliott?source=post_header_lockup">Eric Elliott</a> about closure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4291309d787b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>