<?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 Bobby Tate on Medium]]></title>
        <description><![CDATA[Stories by Bobby Tate on Medium]]></description>
        <link>https://medium.com/@bobby.tate?source=rss-c3b9ccbba72f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*VbD17_eIaHlPA7lyKTAYig.jpeg</url>
            <title>Stories by Bobby Tate on Medium</title>
            <link>https://medium.com/@bobby.tate?source=rss-c3b9ccbba72f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:29:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bobby.tate/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[Essential “this” concepts in JavaScript]]></title>
            <link>https://medium.com/@bobby.tate/essential-this-concepts-in-javascript-8a3c2bb4441a?source=rss-c3b9ccbba72f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a3c2bb4441a</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[code-school]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Bobby Tate]]></dc:creator>
            <pubDate>Mon, 25 Jul 2022 17:40:20 GMT</pubDate>
            <atom:updated>2022-07-25T17:40:20.259Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quick Wins With Code</h4><h4>Execution context, implicit and explicit binding, arrow functions, and of course, this.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xah0hROl1z6RjUBP" /><figcaption>Photo by <a href="https://unsplash.com/@clintbustrillos?utm_source=medium&amp;utm_medium=referral">Clint Bustrillos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To me, a competent understanding of the keyword this in JavaScript feels just about as hard to master as the final boss in a D&amp;D campaign.</p><p>I am not prepared.</p><p>My instinct therefore tells me I should write an article on the subject so that I can attempt to move this from my <strong>passive</strong> vocabulary to my <strong>active</strong> vocabulary.</p><p>Join me on this quest, and let’s level up together.</p><h3>Levels 1–4: Local Heroes</h3><p><em>Defining execution context, </em><em>this, and </em><em>new.</em></p><p>Before we look at this, it will be helpful to define <strong>execution context</strong>. MDN describes <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth#javascript_execution_contexts">execution context</a> in this way:</p><blockquote>When a fragment of JavaScript code runs, it runs inside an execution context. There are three types of code that create a new execution context:</blockquote><blockquote>The global context is the execution context created to run the main body of your code; that is, any code that exists outside of a JavaScript function.</blockquote><blockquote>Each function is run within its own execution context. This is frequently referred to as a “local context.”</blockquote><blockquote>Using the ill-advised <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval()</a> function also creates a new execution context.</blockquote><blockquote>Each context is, in essence, a level of scope within your code. As one of these code segments begins execution, a new context is constructed in which to run it; that context is then destroyed when the code exits.</blockquote><p>Put simply, <strong>an execution context is a created space that directly surrounds a block of running code.</strong></p><p>A <strong>global</strong> context is created at the start of a program. Each time a function is invoked, a <strong>local</strong> execution context gets created and is added to the execution context stack (the call stack).</p><p>I see other articles refer to execution context as the “environment” surrounding your block of running code, which makes sense, because it’s more than just a location!</p><p><strong>An execution context also has custom properties.</strong></p><p>These properties are a little different between global and local context, and between different types of local context (functions vs arrow functions vs classes, etc).</p><p>Something that <strong>every</strong> execution context has however, is a property known as this.</p><p>So what is this?</p><p><strong>Drum roll…</strong></p><p><strong>this is a reference to an object.</strong></p><p>But what object? Well, that depends. Time to run through some examples to start figuring it out.</p><p>In our first simple example, we log the value of this in the global execution context, outside of any function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3214422bcd4a7baee87da4b8d51cbc5/href">https://medium.com/media/c3214422bcd4a7baee87da4b8d51cbc5/href</a></iframe><p>In the browser, we see that this equals the window object.</p><p>MDN confirms the behavior in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#global_context">this definition</a>:</p><blockquote>In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.</blockquote><p><strong>SIDE NOTE:</strong> In the browser the global object is window. In Node.js, the global object is actually an object called global. There are some slight behavioral differences though. In Node.js, the example above would actually log the current module.exports object, not the global object. 🤷 Let’s avoid that rabbit hole for now.</p><p>In this next example, we log this inside a function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/115381eb672fd21ee16dca97155289d2/href">https://medium.com/media/115381eb672fd21ee16dca97155289d2/href</a></iframe><p>At first, you might think that this will evaluate to something other than window, seeing as we created a new local execution context upon invoking the function on line 5, which the code inside our function runs within.</p><p>But as a default (when <strong>not</strong> using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, another rabbit hole 🤷‍), unless <strong>explicitly</strong> set (which we will get to), this still references window.</p><p>MDN confirms this <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#function_context">default behavior</a>:</p><blockquote>Inside a function, the value of this depends on how the function is called.</blockquote><blockquote>Since the following code is not in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, and because the value of this is not set by the call, this will default to the global object, which is <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> in a browser.</blockquote><p><strong>SIDE NOTE: </strong>There is a weird difference in behavior between the browser and Node.js in this second example. In the browser, this equals window, but in Node.js, this equals global this time, instead of the module.exports object. This is due to the difference in how Node.js handles the default value of this between global and local contexts.</p><p>The next example expands on this having a different value based on <strong>how</strong> the function is called:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b343a1e949582b5e9349c81efb9d8559/href">https://medium.com/media/b343a1e949582b5e9349c81efb9d8559/href</a></iframe><p>When we call logThisInAFunction() and myImportantObject.logThisInMyObject(), the same function is ultimately being invoked. However, the value of this is not the same for the two invocations. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#as_an_object_method">MDN again eloquently describes</a>:</p><blockquote>When a function is called as a method of an object, its this is set to the object the method is called on.</blockquote><p>Put simply, if you call a function as a method of an object, that object is going to become the value for this instead of the global object. In this way, we are <strong>implicitly</strong> binding the value of this to an object of our choosing.</p><p>The next example looks at how this behaves for <strong>classes</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46cd017da4633df57f4e81bf38af1266/href">https://medium.com/media/46cd017da4633df57f4e81bf38af1266/href</a></iframe><p>When creating an instance of a class using the new keyword, a new empty object is created and set as the value of this. Any properties added to this in the constructor will be properties on that object.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#class_context">As MDN puts it</a>:</p><blockquote>The behavior of this in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">classes</a> and functions is similar, since classes are functions under the hood. But there are some differences and caveats.</blockquote><blockquote>Within a class constructor, this is a regular object. All non-static methods within the class are added to the prototype of this.</blockquote><p>Relatively straight forward.</p><h4>Before we level up…</h4><p>Hopefully this is starting to sink in. Having already talked about <strong>implicit</strong> binding, let us explore the next level: <strong>explicit</strong> binding.</p><h3>Levels 5–10: Heroes of the Realm</h3><p><em>Defining </em><em>call, </em><em>apply, and </em><em>bind.</em></p><p>Earlier we saw how we can take a function, add it as a method to an object, and when we invoke that method, that object <strong>implicitly</strong> becomes our new value for this.</p><p>Now we want to learn how to <strong>explicitly</strong> set the value of this when invoking a function. We can do that with a few different methods: call, apply, and bind.</p><p>First, an example using call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f58dfd7a629650d43d3ea9af40568c2/href">https://medium.com/media/6f58dfd7a629650d43d3ea9af40568c2/href</a></iframe><p>The first time we invoke useFavoriteSpell, we have undefined values. this has defaulted to referencing the window object, and the properties class and favoriteSpell do not exist on window.</p><p>The next two times we invoke useFavoriteSpell, we are using call to assign the value of this to the object of our choosing, and also invoking the function.</p><p>That is what call does! The first argument of call is the object you want this to equal, and the subsequent comma separated arguments are the function arguments.</p><p>You can read more about call <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">here</a>.</p><p>The next method we will look at is apply. No additional code example is necessary to understand it, in my opinion. The main difference between call and apply is this:</p><ul><li>call accepts function arguments one by one in a comma separated list.</li><li>apply instead accepts all function arguments as one array.</li></ul><p>Outside of some other small differences, they do the same thing. You can read further about apply <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">here</a>.</p><p>Finally, we have bind:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a19d9bf8523f96287474efbd0318189/href">https://medium.com/media/7a19d9bf8523f96287474efbd0318189/href</a></iframe><p>Instead of setting the value of this and also invoking the function, calling bind on our function <strong>just returns a new function</strong>, whose this value is now equal to the object we passed as the argument of bind.</p><p>We can then call our new function whenever we want, and the value of this has already been set.</p><p>Read more on bind <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">here</a>.</p><h4>Before we level up…</h4><p>So now we know about execution context, this, and how to set a value for this both implicitly, and explicitly with call, bind, and apply.</p><p>What else is there? To be honest, there is a lot. But let’s focus on one thing at a time, and move on to the relationship between this and arrow functions.</p><h3>Levels 11–16: Masters of the Realm</h3><p><em>How arrow functions affect </em><em>this.</em></p><p>Earlier, I said that every execution context has a property known as this. The behavior with arrow functions is a little different, however.</p><p>While the local execution context created by invoking an arrow function <strong>does</strong> still have a value for this, it <strong>does not define it for itself</strong>. It instead will retain the value of this that was set by the next outer execution context from where the function was invoked.</p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/279970f0ebb5139a05e4a63621e5d169/href">https://medium.com/media/279970f0ebb5139a05e4a63621e5d169/href</a></iframe><p>We see when we call myImportantObject.logThisInMyObject() that even though a new local execution context was created, this is going to get its value from the next outer execution context. In this case, it is the global execution context. Therefore, this remains a reference to the window object.</p><p>Here is another example that hopefully will drive it home:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5d3707cd66f65814affc4a25b2c48df/href">https://medium.com/media/b5d3707cd66f65814affc4a25b2c48df/href</a></iframe><p>In this example we have two methods we call from myImportantObject: exampleOne() and exampleTwo().</p><p>When we call myImportantObject.exampleOne(), we are invoking that function as a method of an object, and therefore, this equals myImportantObject in that local context.</p><p>However, inside that function, we define another function and then execute it.</p><p>As previously mentioned, unless <strong>explicitly</strong> set, and unless the function is being invoked as a method of an object, this references the global object, window. Therefore, we see window logged.</p><p>When we call myImportantObject.exampleTwo() however, something different happens. The first part is the same: this equals myImportantObject inside exampleTwo. Next, we define an arrow function and then execute it. The difference is, <strong>the arrow function does not define its own value for </strong><strong>this! </strong>It instead retains the value of this from the next outer execution context, which in this example, was the local context created by myImportantObject.exampleTwo(), where this equalled myImportantObject. So that is what we see logged.</p><h4>Before we level up…</h4><p>Arrows functions differ from regular functions in plenty of other ways. If you want to read more, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">check out MDN’s page on the topic</a>.</p><p>If you have made it to this point in the article, it should hopefully mean that things are starting to sink in. Take a moment to relish in your achievement.</p><p>There’s only one section left. Let’s dive in.</p><h3>Levels 17–20: Masters of the World</h3><p><em>Callbacks.</em></p><p>Before I started writing this article, I thought the last section was going to be the most difficult to tackle. In the past, examples of how this got its value in callback functions confused me.</p><p>With the context I now have, it no longer feels like callback functions add any more complexity to how this works. We just need to consider what we already know about execution context, and how we invoke a function.</p><p>I guess the final boss is starting to look a little more beatable 😁.</p><p>Here is an example of using this within callback functions. See if you can guess what the values logged for each will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9525be17c72452b813d105a4e96c553/href">https://medium.com/media/d9525be17c72452b813d105a4e96c553/href</a></iframe><p>Starting with our first function call (where the argument is callbackFunction):</p><ul><li>higherOrderFunction is invoked, and creates a local execution context. Because it is not implicitly or explicitly set, this defaults to window.</li><li>Our callback function is invoked inside higherOrderFunction via myImportantObject.callMyCallback(). Because our callback is <strong>not</strong> an arrow function, the created local execution context defines its own this. And, because that function is being invoked as a method of myImportantObject, this equals myImportantObject.</li></ul><p>Next, let’s look at the second function call (where our argument is callbackArrowFunction):</p><ul><li>higherOrderFunction is invoked just as before. Same outcome: this equals window in that local context.</li><li>Our callback is once again invoked inside higherOrderFunction. This time, because our callback <strong>is</strong> an arrow function, it <strong>does not</strong> define its own this. So even though it is being invoked as a method of myImportantObject, this retains the value of the next outer execution context, which was window.</li></ul><p>The moral of the story is, callback functions add complexity only in the sense that you have to consider <strong>how</strong> (and also <strong>where</strong> for arrow functions) the callback is being invoked.</p><p><strong>But we were considering that already!</strong></p><p>The difference is that callback functions are passed as arguments to other functions, and so where and how they get invoked is a little different.</p><h4>Parting Thoughts</h4><p>Hopefully I didn’t lose you at some point 😅.</p><p>As a developer, I am always trying to continue my education — and I recognize that there is <a href="https://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect">still so much I do not know</a>.</p><p>this is a big subject, and I am sure that there are aspects of the concept that I missed, or examples and explanations that could be improved. <strong>Let’s help each other by trying to figure out what those were!</strong> Feel free to leave a comment, and let me know if this article helped you, and/or what could have been improved.</p><p>Thanks for reading! 😄 Check out some of my earlier articles at <a href="https://www.quickwinswithcode.com/">quickwinswithcode.com</a>.</p><h4>Resources</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth">In depth: Microtasks and the JavaScript runtime environment</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict Mode</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">Function.prototype.call()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">Function.prototype.apply()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">Function.prototype.bind()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow function expressions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a3c2bb4441a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generators and Iterators in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/generators-and-iterators-in-javascript-115bb94ed4f6?source=rss-c3b9ccbba72f------2</link>
            <guid isPermaLink="false">https://medium.com/p/115bb94ed4f6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bobby Tate]]></dc:creator>
            <pubDate>Mon, 06 Dec 2021 10:28:12 GMT</pubDate>
            <atom:updated>2021-12-06T10:28:12.564Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quick Wins With Code</h4><h4>What are generator functions? Should I care?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BnjMQYO04Vw5sGKe" /><figcaption>Photo by <a href="https://unsplash.com/@gregwillson?utm_source=medium&amp;utm_medium=referral">Greg Willson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Whether or not you should care about generator functions is debatable. I did not use them once during my first development job, and neither did my coworkers. I was there for almost three years.</p><p>I do think generator functions are worth understanding, however, for two reasons:</p><ol><li>To avoid being blindsided during a technical interview.</li><li>Constant learning should be one of your goals as a developer.</li></ol><p>To be honest, reason #1 is what initially compelled me to dig deeper. But I am glad that I did because I found it interesting. And as luck would have it, I now work somewhere that uses generator functions alongside a library called <a href="https://redux-saga.js.org/">redux-saga</a>. So it actually benefited me!</p><p>So what is a generator function? To answer that, I first want to talk about:</p><h3>Iterables and Iterators, oh my.</h3><p>An iterable is a fancy word for any JavaScript object that defines for itself how it will behave when it is being looped (iterated) over.</p><p>Here’s how <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#iterables">MDN</a> puts it:</p><blockquote>An object is <strong>iterable</strong> if it defines its iteration behavior, such as what values are looped over in a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> construct. Some built-in types, such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">Map</a>, have a default iteration behavior, while other types (such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>) do not.</blockquote><p>So how do I make my own iterable object? To do that, I would need to implement <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol"><strong>the iterable protocol</strong></a>.</p><p>The iterable protocol (protocol is just a fancy word for an agreed-upon way to do a thing) just asks that you add a property called Symbol.iterator to your custom object. That is it.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/271935eb909e08f5de8c1d5f46091339/href">https://medium.com/media/271935eb909e08f5de8c1d5f46091339/href</a></iframe><p>What does the value of Symbol.iterator need to be, you might ask?</p><p>The value of Symbol.iterator needs to implement another protocol (🤦‍♂️), called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol"><strong>the iterator protocol</strong></a>.</p><p>Per <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#iterators">MDN</a>:</p><blockquote>Specifically, an iterator is any object which implements the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol">Iterator protocol</a> by having a next() method that returns an object with two properties:</blockquote><blockquote>value</blockquote><blockquote>The next value in the iteration sequence.</blockquote><blockquote>done</blockquote><blockquote>This is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator&#39;s return value.</blockquote><p>Let me give you a visual.</p><p>For this next example, let us pretend I already created a function called generateMonster ahead of time. Every time it is called, it spits out a different procedurally generated monster from scratch. Such wow.</p><p>Let us also pretend for now that generateMonster is synchronous.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/712fcbeeba280ce46e470140f4278d53/href">https://medium.com/media/712fcbeeba280ce46e470140f4278d53/href</a></iframe><p>Once we have defined the value for the Symbol.iterator property on our custom object (using the iterator protocol), we can then use it in a for...of loop. The log output of the code above would be five unique monsters.</p><p>We could also manually iterate over our monsterList, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34ac8d62945dc092b4fcdcfeb7a09d3e/href">https://medium.com/media/34ac8d62945dc092b4fcdcfeb7a09d3e/href</a></iframe><p>This provides us a way to step through monsterList at our own pace. For example, we may want to get the first monster but then do some other stuff, and then come back and get the other monsters. The iterator protocol lets us do that.</p><p>Great success! We have now created our own custom object that conforms to the iterable and iterator protocols.</p><p>Do you know what else conforms to the iterable and iterator protocols?</p><p>Take a guess.</p><h3>Generators (finally)</h3><p>Now that we have some background, we can arrive at a more clear understanding of what a Generator is, and how to produce one with a generator function.</p><p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">MDN</a>:</p><blockquote>The <strong>Generator</strong> object is returned by a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">generator function</a> and it conforms to both the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol">iterable protocol</a> and the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol">iterator protocol</a>.</blockquote><p>Put simply, a generator function gives us a Generator object. That object handles the implementation of the <strong>iterable</strong> and <strong>iterator</strong> protocols for us.</p><p>Using a generator function, here is what monsterList could look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/950898b56fb3c6561d4fa9b785f72f60/href">https://medium.com/media/950898b56fb3c6561d4fa9b785f72f60/href</a></iframe><p>The code above will behave in exactly the same way as it did earlier.</p><p>Here are the new things:</p><ol><li>function*. This asterisks next to the function keyword is what designates it as a generator function.</li><li>yield. This keyword is equivalent to returning an object with value and done properties like we did earlier, except it simplifies things for you and just lets you return a value.</li></ol><p>After each yield, <strong>that iteration of the generator function is complete</strong>. At that point, the generator function essentially pauses.</p><p>The function will not continue to execute until the next time .next() is called, whether that be done manually or under the hood in a for...of loop, just like in our earlier example.</p><p>As soon as there are no further yield’s within the function, the generator function returns undefined before terminating, and so the final value of .next() would be {value: undefined, done: true}.</p><p>The example above actually only makes use of half of the value of the Generator object, however. We are currently only using it for its implementation of the <strong>iterator </strong>protocol. We are still implementing our own <strong>iterable </strong>protocol, because we are still creating our own custom object and assigning a value for Symbol.iterator.</p><p>If we want to take full advantage of generator functions, we can simplify our code even further:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d911c281617e0a22b6e70d38ac5c5ae0/href">https://medium.com/media/d911c281617e0a22b6e70d38ac5c5ae0/href</a></iframe><p>Now we are making full use of the generator function syntax.</p><h3>Async Generators</h3><p>Let us now presume my generateMonster function returns a Promise. Luckily, we can still use generator functions to get a bunch of monsters asynchronously.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ef6ec8de7a11718fa1756ebe9876a81/href">https://medium.com/media/4ef6ec8de7a11718fa1756ebe9876a81/href</a></iframe><p>And if you wanted to run this in an asynchronous for...of loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/422d64d71bb045adb9291b23396e276f/href">https://medium.com/media/422d64d71bb045adb9291b23396e276f/href</a></iframe><p>The new things are:</p><ol><li>We use the async keyword before our generator function, monsterList.</li><li>We use the await keyword before we call generateMonster.</li><li>If we want to manually iterate through our Generator using .next(), we need to grab <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator">Symbol.asyncIterator</a> instead of Symbol.iterator.</li><li>If we want to run our Generator object through a loop, we do this using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of">for await...of</a>. In addition, we have to wrap that loop in an asynchronous environment. I chose to wrap it in an async <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE</a> for this example.</li></ol><h3>What is the point?</h3><p>A generator function lets you iterate through values that are being created on the go, which is pretty cool. This can result in better performance because its cheaper than holding a giant data structure in memory and then looping over it.</p><p>To visualize, imagine that you need to collect a mile of rope for some reason.</p><p>With generator functions, it is like pulling that rope out of a magic hat. <strong>You don’t need the whole rope to start collecting it</strong>. You can just pull the rope and get more of it magically as you continue to pull.</p><p>The contrast would be that there is a massive length of rope sitting next to you, taking up space, and you then proceed to grab one end and start collecting it off the floor.</p><p>This quality to generator functions is one of the reasons why they are a fairly good way to express a stream of data. You can get some data incrementally and do stuff with it, while it is arriving.</p><h3>Parting Thoughts</h3><p>At the end of the day, I do not believe that a problem exists that only a generator function can solve. But part of the fun of coding is that there are so many creative ways to solve the same problem! Knowing how to use generator functions gives you one more tool in your toolbox to do just that.</p><p>And, it shows that you might just possibly know what you are doing with JavaScript.</p><p>Thanks for reading! 😄 Check out some of my earlier articles at <a href="https://www.quickwinswithcode.com/">quickwinswithcode.com</a>.</p><p><em>If any of the stuff on asynchronous programming in this article was confusing, check out my other article on the topic:</em></p><p><a href="https://codeburst.io/quick-wins-with-code-promises-in-javascript-4a5b09bd95c5">Quick Wins with Code: Promises in JavaScript</a></p><p><strong>Resources:</strong></p><ul><li><a href="https://redux-saga.js.org/">Redux-saga</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration Protocols</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterators and Generators</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">Generator</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator">Symbol.asyncIterator</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of">for await…of</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE</a></li></ul><p><em>More content at</em><strong><em> </em></strong><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><strong><em>.</em></strong><em> Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter here</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=115bb94ed4f6" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/generators-and-iterators-in-javascript-115bb94ed4f6">Generators and Iterators in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inheritance Vs. Composition in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/inheritance-vs-composition-in-javascript-174142a25bc3?source=rss-c3b9ccbba72f------2</link>
            <guid isPermaLink="false">https://medium.com/p/174142a25bc3</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Bobby Tate]]></dc:creator>
            <pubDate>Tue, 14 Sep 2021 09:08:47 GMT</pubDate>
            <atom:updated>2021-09-14T09:08:47.252Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quick Wins With Code</h4><h4>A brief comparison of two object-oriented programming techniques.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jIZL8HJqrsuu4lPo" /><figcaption>Photo by <a href="https://unsplash.com/@christian_crocker?utm_source=medium&amp;utm_medium=referral">Christian Crocker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I started learning to code, object-oriented programming was explained to me using <strong>inheritance</strong>, a technique for organizing your classes using a parent-child hierarchy. A child class is given <strong>state</strong> and <strong>behavior</strong> from its parent class, and can then add additional state and behavior, becoming even more specific.</p><p>For instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2b892e1f9dcaee72ac64f545177ce85/href">https://medium.com/media/f2b892e1f9dcaee72ac64f545177ce85/href</a></iframe><p>In the example above, both Jedi and Sith classes can use the forcePush method, because they both inherit that ability from their shared parent class, the ForceUser. Only the Sith class can use the forceChoke method and only the Jedi can use the mindTrick method, however.</p><h4><em>What are some of the benefits of this inheritance approach?</em></h4><ul><li>I don’t have to rewrite the forcePush method, because it is being provided to all children of the ForceUser class automatically.</li><li>I created a hierarchy of code that clearly represents the relationships between the parents, children, and siblings.</li></ul><p>But the truth is, the force is more nuanced than this. My rigid hierarchy doesn’t do it justice.</p><p>When I was in high school playing <em>Star Wars Jedi Knight: Jedi Academy</em> every waking moment, Jedi Master Kyle Katarn taught his pupils that all abilities of the force are open to a Jedi. It is how you use those abilities that defines your alignment.</p><p>That being said, I have clearly run into a problem with the inheritance model. I cannot create a Jedi that can also force choke. Only the Sith class has that ability. Lame.</p><p><em>Well what if I:</em></p><ul><li>Just duplicate some code and add the forceChoke method to the Jedi class?</li><li>Just add forceChoke to the ForceUser class? That way, both Jedi and Sith inherit it?</li></ul><p><strong>Both of these options are kind of terrible.</strong></p><p>The first option implies I will have two implementations of forceChoke. What if I need to update that method? I have to do it in two places now. I’ve lost my single source of truth. Also, I duplicated code. In general, this is something usually worth avoiding.</p><p>The second option implies all Jedi and Sith can use forceChoke. But how many Jedi actually need this ability? I have now given all Jedi an ability that the majority of them will never use. I am heading in the direction of a “God Object” — moving behaviors and state up the hierarchy of ancestors, so that more child classes can inherit them. That is a <a href="https://en.wikipedia.org/wiki/Code_smell">code smell</a>.</p><p><strong>This is where the argument for composition over inheritance comes in.</strong></p><p>Composition is when you write your code in such a way that objects/classes are organized by <strong>what they can do</strong>, versus trying to decide / predict entirely <strong>what they are</strong>,<strong> </strong>now and always.</p><p>With inheritance, you have to do guesswork when you first plan out your code. With composition, you can just mix and match behaviors without sacrificing flexibility.</p><p>Here’s an example of composition using functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c136cfea6964f98f6ec7b5f2d6334c8/href">https://medium.com/media/3c136cfea6964f98f6ec7b5f2d6334c8/href</a></iframe><p>In the example above:</p><ul><li>I define some functions which return (as object literals) the behaviors I want to compose together.</li><li>I define a ForceUser function, pass it a name, and save the name inside an object called state.</li><li>ForceUser returns an object (using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals">spread syntax</a>), which is composed of the behaviors I want to provide. Now, kyle is an object that has all of the behaviors I want it to. And, because of a <a href="https://medium.com/swlh/quick-wins-with-code-closures-in-javascript-deda4113055c">closure</a>, the behaviors are all permanently able to reference any values from the state object.</li></ul><p>I now have an implementation of ForceUser that has only the behaviors it needs.</p><p>We are no longer restricted by concepts such as Jedi and Sith.</p><p>I have seen plenty of variants of the previous example around the internet. <strong>Something I have found less of are examples of using composition while still using ES6 class syntax.</strong></p><p>I wanted to take a stab at how one might do that. If this helps you, great. If this offends your sensibilities, I apologize.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eb45be7c64cb36d2d75cd2dd955661d/href">https://medium.com/media/6eb45be7c64cb36d2d75cd2dd955661d/href</a></iframe><p>In this example:</p><ul><li>I start out the same by defining some functions which return behaviors as object literals. I decided to rename state to self however, which I’ll get to.</li><li>I define a ForceUser class. Notice I still defined forcePush as a method on the class. That is because I am fairly confident a ForceUser should always have that ability.</li><li>To add additional state and behavior I’m doing some setup work in the constructor. I created a method called addToClass which takes either state or behavior, and adds it to the class instance using the this keyword. It’s kind of a low-level helper method which lets me add state or behavior from object literals when I’m creating an instance of the class.</li><li>When stateObj is passed to addToClass() , it’s pretty straight-forward. When I pass behaviorComposer however, I’m passing the function as a callback. It then gets called inside the constructor, and is passed the context of that instance with this. That way, the behaviors all have access to the state. So wherever you see self referenced, it’s equivalent to this.</li></ul><p>I now have a ForceUser class that gives forcePush to everyone, and other behaviors can get added à la carte.</p><p>I like this approach, but the addToClass method is completely unrelated to a ForceUser. I felt like it would be worth separating out somehow, and I actually ended up using inheritance do so; separating the lower level functionality into its own parent class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68342058c3039def4fe495c49484eb18/href">https://medium.com/media/68342058c3039def4fe495c49484eb18/href</a></iframe><p>I like this implementation even more. Using inheritance to separate out logic based on its level of abstraction seems like a halfway decent reason to create a parent-child relationship. Now, my ForceUser class feels really lean. I don’t even need to define a constructor in this case (there’s a default one for derived classes being used under the hood).</p><p>I also opted to put my behaviorComposer callback argument inline, instead of defining it outside of where I create an instance of the class. That’s just a personal preference thing.</p><h3>Parting Thoughts</h3><ul><li>I like Star Wars.</li><li>I prefer composition over inheritance, but there might be a time and a place for both.</li><li>You should probably stick mostly with composition though. Hopefully, this article has helped you understand some ways to do so.</li></ul><p>Thanks for reading! 😄 Check out some of my earlier articles at <a href="https://www.quickwinswithcode.com/">quickwinswithcode.com</a></p><h4>Resources:</h4><ul><li><a href="https://en.wikipedia.org/wiki/Code_smell">Code Smell</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals">Spread Syntax</a></li><li><a href="https://medium.com/swlh/quick-wins-with-code-closures-in-javascript-deda4113055c">Closures</a></li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=174142a25bc3" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/inheritance-vs-composition-in-javascript-174142a25bc3">Inheritance Vs. Composition in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Wins with Code: Promises in JavaScript]]></title>
            <link>https://codeburst.io/quick-wins-with-code-promises-in-javascript-4a5b09bd95c5?source=rss-c3b9ccbba72f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a5b09bd95c5</guid>
            <category><![CDATA[web-dev-bootcamps]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bobby Tate]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 22:15:44 GMT</pubDate>
            <atom:updated>2020-07-29T22:15:44.400Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick look at handling asynchronous code in JavaScript.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1UTzQEFWBrMqtPqp" /><figcaption>Photo by <a href="https://unsplash.com/@ethankent?utm_source=medium&amp;utm_medium=referral">Ethan Kent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Like a dog waiting for their human to return, programmers often wait for their code to return something. Perhaps it’s JSON from a REST endpoint you hit from the client. Perhaps it’s a record from a database you queried from the server.</p><p>Perhaps it’s the human, coming home with treats.</p><p>Thankfully, we can do other stuff while we wait! A program can continue executing other code while requests for external resources continue to sit patiently in the background, stepping out of the way so that other code can continue to run. <strong>When the code that was waiting on something finally receives that thing, it can then follow up by doing something that it was holding off on doing until it first got what it needed.</strong></p><p>To keep up the dog analogy a little longer — this behavior equates to the idea of a dog waiting for its owner to get home before it is let out to do its “business”. However, while the dog is waiting, it chews up a pillow, runs around the house eight times, and barks for twenty minutes. Those actions weren’t dependent on the human returning, so they just happen. Thankfully, the dog at least knows to hold it in the meantime.</p><p>This idea of <strong>non-blocking</strong> code execution is called <strong>asynchronous</strong> <strong>programming</strong>.</p><p>In JavaScript, we can handle asynchronous code with something called callback functions (<a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">see MDN’s doc on callbacks</a>). Callback functions are great, but they’re not always the tool I want to reach for. There’s another tool. For the types of calls where we are waiting on a resource from an external source, I prefer to use the Promise object<strong>.</strong></p><p><strong>What is a promise?</strong></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN’s page</a> on the Promise object nails the definition, so I will defer to them:</p><blockquote>The <strong>Promise</strong> object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.</blockquote><p>A <strong>Promise</strong> is a JavaScript object that helps us handle the timing of asynchronous operations. We can wrap the code we want to run asynchronously in a Promise, which will help us detect when that operation has successfully (or unsuccessfully) completed. We can then trigger follow up code that depended first on a promise fulfillment, or that handles a promise rejection.</p><p>Since I started learning JavaScript, I have worked with two prevailing implementations for utilizing promises. They are promise chaining with .then(), and async await.</p><p>People seem to have strong feelings about which one is better.</p><p>Below are code examples for the same bit of logic written out twice, showing the use of .then() in the first, and the use of async await after that. They both are using a <a href="https://www.npmjs.com/package/node-fetch">node.js implementation</a> of the fetch() API, which returns a promise (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">here’s MDN’s page on the Fetch API</a>).</p><p>.then() :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32bc25b4144f87039e8654e64d1c3827/href">https://medium.com/media/32bc25b4144f87039e8654e64d1c3827/href</a></iframe><p>What I’m doing here is calling the <a href="https://pokeapi.co/">pokeapi</a> endpoint, extracting the JSON body content from the response with .json(), and then writing it to a file locally with the fs node library.</p><p>But the real magic here is .then(), which allows me to specify what happens after a response is received from a promise.</p><p>You can read it like:</p><ul><li>Fetch data from a REST endpoint.</li><li>.then() once I’ve got something, extract the usable part (the JSON).</li><li>.then() once it is usable (.json() also returns a promise), write the data onto a file.</li></ul><p>Stringing .then() blocks one after the next is why this method of handling promises is also called <strong>promise chaining</strong>.</p><p>Next, we have an example of the same thing, but using async await:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3bcc351b8b70f523b01bb2e9066b462/href">https://medium.com/media/b3bcc351b8b70f523b01bb2e9066b462/href</a></iframe><p>To implement this, you just put the async keyword before your function declaration. For calls inside the function that return promises, put the await keyword before those.</p><p>This can be read like:</p><ul><li>Wait for the return content from the fetch() request.</li><li>Wait for the .json() method to extract the JSON body content.</li><li>Write the data to a file.</li></ul><p>Using await actually stops the execution of subsequent lines of code within the async function, until the promise on that line is fulfilled. Because of this, it feels a bit more magical. It reads more like synchronous code, as if you never were actually waiting for anything.</p><p>My personal preference is to use promise chaining. I like the way it flows more, and I think it more clearly shows that you are dealing with asynchronous code. I’m also not a fan of the fact that I’ve created a lexical environment in my async await example, where by the time I’m writing to a file, I still have access to the response value. That just seems sloppy to me.</p><p>I also prefer how promise chaining handles errors. With promise chaining, all errors can be handled with one final .catch() block at the end of your chains of .then()&#39;s.</p><p>Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96a832a78c3eba48d6d4a11303f11b17/href">https://medium.com/media/96a832a78c3eba48d6d4a11303f11b17/href</a></iframe><p>With async await, the main example I’ve seen is to use a try catch block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8782fd61e69e5ac23ad1b270c2e60034/href">https://medium.com/media/8782fd61e69e5ac23ad1b270c2e60034/href</a></iframe><p>It’s not the worst, but it’s just a little more difficult to reason about, in my opinion.</p><h3>Conclusion</h3><p>So what have we learned today?</p><ul><li>Programs are like dogs.</li><li>A promise is like a dog waiting for their owner to come home before relieving themselves. But the dog (a program), can continue to do other dog things in the meantime.</li><li><a href="https://pokeapi.co/">There’s a REST API for Pokemon</a> (this might be the most important lesson).</li><li>People have strong opinions.</li><li>Promises are pretty amazing, and you should try using them either with .then(), or with async await.</li></ul><p><em>This article is part of a series on digestible code concepts for folks newer to web development, who are searching for better approaches to solving problems with code.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a5b09bd95c5" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/quick-wins-with-code-promises-in-javascript-4a5b09bd95c5">Quick Wins with Code: Promises in JavaScript</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Wins With Code: Closures in JavaScript]]></title>
            <link>https://medium.com/swlh/quick-wins-with-code-closures-in-javascript-deda4113055c?source=rss-c3b9ccbba72f------2</link>
            <guid isPermaLink="false">https://medium.com/p/deda4113055c</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[web-dev-bootcamps]]></category>
            <category><![CDATA[code-camp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lexical-scope]]></category>
            <dc:creator><![CDATA[Bobby Tate]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 15:28:26 GMT</pubDate>
            <atom:updated>2020-07-23T05:49:38.504Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What is a closure in JavaScript? Why do closures matter? How do you use closures?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G_LjNT8CseL6QnUq" /><figcaption>Photo by <a href="https://unsplash.com/@pablothewarrior?utm_source=medium&amp;utm_medium=referral">Pablo Guerrero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Seeing as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">MDN’s page on closures</a> defines it extremely well, I’m not going to reinvent the wheel here:</p><blockquote><em>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the </em><strong><em>lexical </em></strong><em>environment).</em></blockquote><p>Let’s unpack this concept a bit.</p><p>The first thing I want to point out is that whenever you define a function, you are making a choice about its lexical environment, whether intentional or unintentional, conscious or…maybe you’re unconscious. I don’t know.</p><p>In many cases, the lexical environment of a function is just the global scope, because that is where you created it. Don’t worry, there’s nothing wrong with that.</p><p><strong>But the value of a closure becomes more obvious when you intentionally enclose a function into its own lexical environment. </strong>One of the ways you can do this is by wrapping it inside another function. You’ve now created a more specific, local scope.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04d5313af06b1ba72fb81ce3aa69bc4a/href">https://medium.com/media/04d5313af06b1ba72fb81ce3aa69bc4a/href</a></iframe><p>Here we have a rocket function, which has some local variables, and an inner fly function. When I call rocket, it returns a unique instance of an object with the fly function stored inside that object (line 15). It’s important to note that I’m not actually calling fly yet. I’m just returning an object that has the fly function inside it.</p><p>Each time I call the rocket function, I’m returning a separate instance of the fly function, and that instance of fly is <strong>actually holding on to its own instance of its lexical environment, even after </strong>rocket<strong> has completed running.</strong></p><p>That right there is the power of a closure: Each time I call rocket, I’m creating an instance of fly that has a <strong>persisting reference to a unique lexical environment</strong>.</p><p>You can see how this specific use case could be valuable if you’re trying to do something object oriented. We’ve encapsulated state and behavior in a persisting, reusable manner! And we didn’t use class, constructor, this, or new. How about that.</p><p>One other nice thing about doing object oriented programming in this manner is that your state is actually private and inaccessible compared to when you use class syntax from ES2015. You can’t access the name of a rocket with sputnik._name (unless you added it to the returned object of rocket on line 15, but you shouldn’t do that).</p><p>The power to keep private state truly inaccessible is a really good thing. It tells readers how the function should and should not be used. Keep private variables private. This also gives you the option to implement a true “read only” paradigm, if you wanted to.</p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/826c199e5d553034a82c90fe6157e4ea/href">https://medium.com/media/826c199e5d553034a82c90fe6157e4ea/href</a></iframe><p>I’ve added name access in the object returned by rocket on lines 17–19, using get syntax. I can now read the _name property, but I don’t have the ability to change it. That’s exactly the kind of guardrail that I wanted to implement. Great success!</p><p>Sorry for the tangent on private state. I just think it’s one of the cooler things closures make possible.</p><p><strong>Here’s one last example of a closure in action:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f5bed26e1f188f5fa5a2425c4500412/href">https://medium.com/media/0f5bed26e1f188f5fa5a2425c4500412/href</a></iframe><p>Here we have a higher-order function (a function that operates on other functions), called moduloFactory. It’s a function that returns other functions, so you could also call it a function factory (thus the word factory in the name).</p><p>So where is the closure? In this example, the closure is the combination of the anonymous function returned by moduloFactory (line 2), and the saved lexical environment that this anonymous function keeps in its back pocket, in the form of the argument passed to moduloFactory at the time it was called.</p><p>So because of closures, we can pump out as many unique instances of that inner function as we want, and each one will keep a reference to whatever lexical environment we choose.</p><p>Closures are cool, right? They were there all along, you just didn’t notice them. They’re not attention seekers. They’re wallflowers. You kind of have to seek them out, before you really get a sense of who they are. But like most introverts, they are worth the time and effort it takes to get to know them.</p><p>Hopefully I’ve made a nice introduction. 😅</p><p><em>This article is part of a series on digestible code concepts for folks newer to web development, who are searching for better approaches to solving problems with code.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deda4113055c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/quick-wins-with-code-closures-in-javascript-deda4113055c">Quick Wins With Code: Closures in JavaScript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Wins with Code: Event Delegation]]></title>
            <link>https://medium.com/@bobby.tate/quick-wins-with-code-event-delegation-9ceb08d8cbc6?source=rss-c3b9ccbba72f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ceb08d8cbc6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[document-object-model]]></category>
            <category><![CDATA[vanilla-javascript]]></category>
            <category><![CDATA[code-school]]></category>
            <category><![CDATA[event-delegation]]></category>
            <dc:creator><![CDATA[Bobby Tate]]></dc:creator>
            <pubDate>Wed, 15 Jul 2020 23:41:36 GMT</pubDate>
            <atom:updated>2021-10-14T14:08:22.955Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A quick look at using event delegation instead of placing multiple event listeners on a page.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gcuc8MMgplGMzORk" /><figcaption>Photo by <a href="https://unsplash.com/@payam__tahery?utm_source=medium&amp;utm_medium=referral">Payam Tahery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a web page adorned with a lake of buttons. Each one of those buttons does something beautiful and life changing.</p><p>How do you make each of those buttons do something unique?</p><p>With <strong>event listeners</strong>! Any target button with an event listener on it will patiently wait for some designated event to occur, and then run some code.</p><p>Let’s say there are twenty buttons. Do you really want to write out twenty event listeners in our code? Nope. Don’t do it.</p><p>And you may think, “Oh, I’ll just loop through all the buttons and put an event listener on each one. That way, it won’t be as much code on the page.”</p><p>That may produce fewer lines of code, but it doesn’t change the fact that you still just created twenty separate event listeners. That many listeners should leave a bad code smell in your nose.</p><p>Enter <strong>event delegation</strong>.</p><p>The idea behind event delegation is to put one event listener on a common ancestor of all the elements you’re trying to listen to. Then, by using the event object that you have access to inside of event listeners, you can check for what is being clicked, and then do something more specific based on that information.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bcb9ef021bb5203db7c50ff2220cb87/href">https://medium.com/media/5bcb9ef021bb5203db7c50ff2220cb87/href</a></iframe><p>Based on that HTML, let’s say my goal is to change the background color of the &lt;body&gt; element on my web page, based on the specific &lt;li&gt; I click on.</p><p>I could do that with multiple event listeners like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7ef0c127ec9c04493edab9768e0c76a/href">https://medium.com/media/d7ef0c127ec9c04493edab9768e0c76a/href</a></iframe><p><strong>Or, </strong>I could use event delegation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0880e9ce2fe0925553b60f9c3cd43c0b/href">https://medium.com/media/0880e9ce2fe0925553b60f9c3cd43c0b/href</a></iframe><p>Again, the magic here is the use of the event object, which we have access to inside the callback function of our listener.</p><p>The event object has all sorts of useful properties about the event that just triggered the listener. One of those is event.target, which tells me what HTML element in the DOM my event occurred on. With that, I can figure out what was clicked, and do something unique to that element.</p><p>That’s really all you need to know to be dangerous with this pattern.</p><p>Thanks for reading! 😄 Check out some of my other articles at <a href="https://www.quickwinswithcode.com/">quickwinswithcode.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ceb08d8cbc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Wins with Code: Object Literal Lookups]]></title>
            <link>https://medium.com/@bobby.tate/quick-wins-with-code-object-literal-lookups-21d8f3512ac5?source=rss-c3b9ccbba72f------2</link>
            <guid isPermaLink="false">https://medium.com/p/21d8f3512ac5</guid>
            <category><![CDATA[web-dev-bootcamps]]></category>
            <category><![CDATA[conditional-logic]]></category>
            <category><![CDATA[bracket-notation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-dev-resources]]></category>
            <dc:creator><![CDATA[Bobby Tate]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 01:43:34 GMT</pubDate>
            <atom:updated>2021-10-14T13:58:26.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjV1gZNigfli7zTpzrJnmA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ulPd2UCwZYk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nathan Dumlao</a> on <a href="https://unsplash.com/search/photos/menu?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Have you ever thought, “what a giant ugly switch statement” or thought the same about a giant chain of else-if statements? Or a giant nested ternary operator?</p><p>For instance, let’s say you need to write a function that returns specific HTML based on the type of media provider you pass in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f13c3a62137f0b36ed116a04bc59dbaf/href">https://medium.com/media/f13c3a62137f0b36ed116a04bc59dbaf/href</a></iframe><p>That’s fairly ugly, right?</p><p>Enter object literal lookups — a way of writing conditional logic that’s much more like selecting your choice from a menu.</p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cefcb5f672ec49c4ee7563be4c45835c/href">https://medium.com/media/cefcb5f672ec49c4ee7563be4c45835c/href</a></iframe><p>The idea is to write a function that returns a value from an object literal. The argument you pass it determines what you get back. That magic is powered by bracket notation, on line eight above. Bracket notation lets you use the provider variable to dynamically return the property value you want to access.</p><p>Here is another example, in order to solidify the concept a little more. Please do not critique it on the basis of its naming conventions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4a39bb1a0e01af27fd898425b53153c/href">https://medium.com/media/d4a39bb1a0e01af27fd898425b53153c/href</a></iframe><p>This one is fun, because it shows you can also give these bad boys a default value. In this instance, if you do not pass in an argument, the monkey doesn’t have anything to hold, sadly.</p><p>Now if you’ll excuse me, I need to go refactor this so that the monkey is replaced with me, and all the options are bourbon.</p><p>Thanks for reading! 😄 Check out some of my other articles at <a href="https://www.quickwinswithcode.com/">quickwinswithcode.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21d8f3512ac5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>