<?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 Sergio Valverde on Medium]]></title>
        <description><![CDATA[Stories by Sergio Valverde on Medium]]></description>
        <link>https://medium.com/@sergio.valverde.b?source=rss-d3c983f58e4c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kuv1P0cZWtoP_F00Wp_jfg.jpeg</url>
            <title>Stories by Sergio Valverde on Medium</title>
            <link>https://medium.com/@sergio.valverde.b?source=rss-d3c983f58e4c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:34:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergio.valverde.b/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[Modern Javascript and Asynchronous Programming: Generators/Yield vs. Async/Await]]></title>
            <link>https://medium.com/front-end-weekly/modern-javascript-and-asynchronous-programming-generators-yield-vs-async-await-550275cbe433?source=rss-d3c983f58e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/550275cbe433</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sergio Valverde]]></dc:creator>
            <pubDate>Thu, 11 Jan 2018 23:51:04 GMT</pubDate>
            <atom:updated>2018-11-09T16:41:03.848Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Since the 6th version of the ECMAScript specification was released back in 2015, there have been several new features introduced or proposed for the JavaScript language that are focused on providing easier ways to handle asynchronous programming, or dealing with collections of objects (like iterables/iterators). These two topics overlap when considering asynchronous streams of data, the observable pattern, and reactive programming in general, with all the relationships between data producers and consumers. This is a very broad topic, so understanding first Generator Functions/Yield and Async/await can serve as a good introduction to some of these concepts.</em></p><p>Back in 2015, ES6 (ES2015) introduced the now very popular promises. A promise is an object that works like a contract, like an agreement that an asynchronous function will either resolve to a value or to an error. Promises are not the focus of this article, but they are really a foundation of the following topics, so make sure you understand them well first. There are excellent resources that explain promises in depth, one of my favorites is <a href="https://www.youtube.com/watch?v=2d7s3spWAzo">Mattias Petter Johansson’s Fun Fun Function video about Promises</a>.</p><p>ES2015 also introduced Generator functions and the keyword yield. <strong>Generators can be used for both synchronous and asynchronous purposes, but it’s important to understand that they are the foundation on which the more popular async/await syntax is built on. </strong>Therefore, if you want to really understand async/await, you should first understand Generator functions, as well as the fact that they can be used for other use cases. Often tutorials start explaining generator functions by showing their usage equivalent to async/await, but this has some drawbacks. First, because generators functions can have other completely different uses which should be mentioned, and two, because it can make it more complicated to understand for someone who is not familiarized with them. Here I will start with the simplest example and then move on to their similarity with async/await.</p><p><strong>The newer async/await syntax was initially proposed around 2015 for ES2017, to be able to write asynchronous code in a way that reads like synchronous code </strong>(without having to use .then() and callback functions). This is also described sometimes as “waiting code”. Async/await is a really useful way to create asynchronous code, which can be more compact and easier to understand than handling promises the regular way. However, they also have their limitations that are important to consider, which I’ll mention below. In some cases, it is still better to handle promises in the older fashion.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><p>Generator Functions (ES2015)</p><p>A generator function is a function that can return multiple values, through intermediate “returns” marked by the keyword yield. <strong>The generator function pauses its execution at each of these points</strong> until it would eventually reach its final return, using the regular “return” keyword, and the function ends. Generator functions are declared by adding an asterisk after the function keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/0*PYW4IcbaPe-U7IBk." /><figcaption><em>This is a very simple example of a generator function. The first time that a value is requested from this generator (we’ll see how to execute it below) it will return the value 5, the next time it will return the value 7, and finally it will return the value 11.</em></figcaption></figure><p>An interesting aspect of generators is that <strong>they provide multiple values on demand, one at a time: they only continue their execution up to the next yield or return when someone else requests it</strong>. This is a concept similar to the observable/observer design pattern, except that generator functions act as a passive producer of values, instead of an active one. An active producer would emit values when it wishes, instead of waiting for someone else to request it. The piece of the code that requests values from the generator function is the active consumer, because it takes the initiative to request values, it isn’t just listening to receive passively.</p><p>So how are they executed?</p><p>To achieve this, when you call a generator function it doesn’t actually run the code of the function, it will immediately (synchronously) return a special type of object called a Generator object. This object functions as an iterator, among other things, so for simplicity’s sake we’ll refer to it here as “iterator”. As the name suggests, it can iterate through a collection of values, in this case, the different “returns” that the generator function can provide (marked by either “yield” or the final “return” keyword). Then, to run the function up to its first “intermediate return”, you call the method next() on the iterator.</p><p>In general, <strong>iterator.next() executes the generator function up until its next stopping point</strong>, whether that’s an intermediate yield statement or the final return. Calling next() always produces an object with a value property and a done property, which is a boolean. This way, you can get the value that you wanted, but you can also know if you can request more values or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/0*mxtBtO81xDkwIHwO." /><figcaption><em>In this example, you can see the generator function being executed, which returns the iterator object. We then use the next method of the iterator to get the values, calling it three times. I’m using an inline evaluation tool (Quokka) that displays the values of each variable, lines 13–15. With the third iteration we receive &quot;done:true&quot; to indicate that no more values can be requested.</em></figcaption></figure><p>In real life use cases you probably wouldn’t know beforehand how many times to request values, so a usual implementation would be to keep requesting values as needed until you receive &quot;done:true&quot;, for example using a while loop. A loop could also be used inside the generator function itself, to keep yielding items one at a time, for example, values from a long list, as long as there are more items to yield. The generator function could even continue providing values infinitely, from sequences that can be calculated that don&#39;t have an end (for example, the Fibonacci sequence).</p><p>A generator function is similar to a state machine (a function that keeps track of its own state), because it remembers the progress of its execution. This is one of the aspects that makes generators useful. A generator function can actually be implemented in ES5 through the use of closures, to return an iterator object that will remember its own state. This is, however, more complicated to write, and it would have to be adapted to each use case. See this ES5 example (with the exception of using const and let, but those can be replaced with var without changing the example’s behavior):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*7EY5h26c4akczwl-." /><figcaption><em>This “fakeGenerator” function works exactly in the same way as the real one, for our limited purposes. It returns an object with a “next” method, that can return values keeping track of which value to return, in this case, thanks to a closure.</em></figcaption></figure><p>Async Functions (ES2017)</p><p>Now, how do generator functions and yield relate to async/await? Async/await is a newer proposal for the upcoming versions of the Javascript language, defined formally in ES2017, which also allows you to write functions that can be paused, but in a more specialized way than generators. <strong>Keep in mind that async/await makes it easier to implement a particular use case of generators. Generator functions/yield and Async functions/await can both be used to write asynchronous code that “waits”, which means code that looks as if it was synchronous, even though it really is asynchronous; it doesn’t use callbacks.</strong></p><p>We’ll first start with generators: Since yield stops the execution of a generator function at a certain point, it can allow for waiting for async requests to complete before continuing. Consider the following example:</p><p>Let’s say in our application we have an “init” function that will retrieve any necessary information from the backend, for example fetching users, which would be an asynchronous method since it involves an XHR request. If we use promises, we would have to define a callback function to execute when the promise resolves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/0*JDulJe3SGciA3j6S." /></figure><p>With generator functions, we can use yield to wait for the async function “getUsersFromDatabase” to resolve, and then just set the returned value as our users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/0*Y1L_u5aEZnowwj00." /></figure><p>This definitely looks easier to read, but it doesn’t work quite so simply. As the term implies, the keyword “yield” really yields the control of execution to whoever called the generator function. This means there must be an external function that is in charge of receiving the yielded promise, waiting until it resolves, and then pushing the result back into the generator function so that it can resume execution and assign that value to the users variable.</p><p>This introduces an aspect of generator functions that we hadn’t seen before: <strong>At any of the “stopping points” in a generator function, not only can they yield values to an external function, but they also can receive values from outside</strong>. This allows for a back-and-forth communication between two pieces of code.</p><p>Passing values into a generator function is achieved by passing them as arguments into the iterator’s “next” method. The following example is an implementation of how the “external” code that calls the generator function is in charge of resolving any promises and sending the resolved value back into the generator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*8fk9y3s3AknGdbil." /><figcaption><em>The implementation of getUsersFromDatabase is not important, it just returns a promise that resolves after two seconds returning the string “Test Users”. Note how the external code (lines 6–30) is in charge of calling the generator (lines 6–7), handling the resolved value of the promise (callback starting at line 16), and sending the value back into the generator (line 20), in order to get the generator’s final value. Lines 13, 18 and 28 are just there to show the values of the variables at that point, indicated by the dark blue text added by the inline evaluation tool.</em></figcaption></figure><p>This is a simple scenario because the code is implemented specifically for a generator function that yields only one value. Ideally, the external functions should be able to handle any number of yielded promises until the generator reaches its final return. This functionality is available as third-party libraries, to be able to write asynchronous waiting code in this fashion with generators/yield without having to worry about how the external function handles and resolves the promises. Those libraries can provide a function that can receive a generator function as an argument, executing the generator and handling any promises yielded.</p><p><strong>This lengthy example serves to show why Async/await is a very useful feature: It lets you write async waiting code like our generator function example (lines 1 to 4), but it doesn’t need any external helper function to handle the promises! </strong>With async/await, you can just write the example like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*LUdzQ27Jx7d9bQJa." /></figure><p>The asterisk notation of generators is replaced by placing the keyword async in front of the function declaration, and “yield” is replaced by “await”. <strong>Await can be placed in front of any statement that returns a promise, and the await keyword can only be used inside functions that are marked by the async keyword before their declaration.</strong> Now when this test function is executed, it will pause at the await keyword, wait for the promise to resolve, and then automatically assign the resolved value to const users, all without the help of any other function.</p><p>Async/await is then really useful to write code dealing with promises without having to call .then() methods, declaring callbacks, and all the nesting that it involves (the infamous pyramid of doom). It seems like a great solution, but there are some important considerations that must be taken into account before using them. In some cases it might be better to just stick with the old way of resolving promises with .then(). You should consider the following:</p><p>1) <strong>Async functions always return a promise:</strong> Since async functions pause their execution at any “await” keyword to wait for asynchronous expressions to resolve, they themselves become asynchronous (and hence why they have the async keyword in front of them). That means that regardless of what you return from that function, functions with the async keyword will <em>always </em>return a promise, that will resolve to whatever you returned, or throw an error. In the previous example, the function “test” returns the string “Test Users Correctly received”, but in reality it will actually return a promise that will resolve to that string. This is important to keep in mind when designing your code and thinking about how other parts of the code are going to interact with any given function, whether they are expecting to receive a promise or not.</p><p>2) <strong>Await can only wait for promises sequentially, not in parallel</strong>. The await keyword can only wait for promises one at a time, not several at once. Therefore, if you have to deal with several promises and you want to wait for them with await, you’ll have to wait for each one to complete before moving on to the next.</p><p>This is much slower than processing multiple promises at the same time, although there are cases where it could be the best decision, for example, if you don’t want to overload a network by sending hundreds of requests at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*6pHUClvZAFoJ71tm." /><figcaption><em>Assume that “users” is an array of users predefined elsewhere, and that “getProfileImage” returns a promise that resolves to a profile image. This example iterates through each user, pausing at each iteration to push the image into a “profileImages” array. It only continues to the next iteration when the promise from the current iteration is resolved.</em></figcaption></figure><p>An alternative if you want to handle several promises at the same time is to combine the use of await and regular promises. For example, you could unify a group of promises with the method “Promise.all”, which will return a single promise that will resolve whenever all of the promises resolve (or throw an error if any of them fail). Then you can use await just on that single unified promise:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*eacvlciILO6GXJ2g." /><figcaption><em>This example iterates through the users array using “map”: For each iteration, it executes “getProfileImage” and returns the pending promise. Notice that map doesn’t pause at each iteration, it just returns an array holding all the promises. Then we can unify all those promises using “Promise.all”, and we use await to pause only at that point, to wait until the single promise resolves.</em></figcaption></figure><blockquote>Keep in mind - Generators and async functions always return a specific type of object:<br>- <strong>Generator functions:</strong> If you yield/return a value X, it will always return an iteration object with the form <em>{value: X, done: Boolean}<br></em>- <strong>Async functions:</strong> If you return a value X, it will always return a promise that will either resolve to the value X or throw an error.</blockquote><p><em>Conclusion</em></p><p>Generators are pausable functions that can generate (yield) values on demand, whenever the iterator object requests the next value. In this sense, they are a passive producer, while the iterator is the active consumer (because it’s the one that takes the initiative to request a value). This is in contrast to the usual observer pattern, where there’s an active producer (the observable/subject) that emits values when it wishes, and one or more passive consumers (the observers) that are just listening to receive values. A possible use of generator functions is to yield values from a long series one at a time, possibly being able to produce infinite values as needed.</p><p>One particular use of Generator functions is to write async code that looks synchronous (code that “waits”), by yielding any promises, but they require the help of another function that would have to handle all the promises. It is better to use async/await for this purpose, since they are able to write code in this way without needing any helper function.</p><p>Async functions and the await keyword are a great way to write asynchronous code that &quot;waits&quot;, but they cannot wait for multiple promises at the same time, so it&#39;s a good idea to fall back to normal promises when await becomes a limitation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=550275cbe433" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/modern-javascript-and-asynchronous-programming-generators-yield-vs-async-await-550275cbe433">Modern Javascript and Asynchronous Programming: Generators/Yield vs. Async/Await</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Strange Case of Arrow Functions and Mr.]]></title>
            <link>https://medium.com/front-end-weekly/the-strange-case-of-arrow-functions-and-mr-3087a0d7b71f?source=rss-d3c983f58e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3087a0d7b71f</guid>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sergio Valverde]]></dc:creator>
            <pubDate>Tue, 26 Dec 2017 17:35:09 GMT</pubDate>
            <atom:updated>2017-12-26T18:54:09.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Strange Case of Arrow Functions and Mr. Context: Understanding “This” in Arrow Functions — Lexical Scope Vs Dynamic Scope</h3><p><em>Arrow functions, and the way they handle context, are great for some use cases, such as being used as callbacks for event handlers, or just passing them around an application without losing their context. However, the way the “this” keyword really works in arrow functions is not as clear as it might first seem. I wanted to write this article to hopefully shine a bit more light on how arrow functions really determine their context. This article doesn’t cover the basic syntax for arrow functions, so I’m assuming you are familiarized with it already.</em></p><p>Ever since arrow functions were introduced in ES6, they have been a useful tool to have a bit more control of the context of a function. One of their main characteristics is that they have a “fixed” context; they retain the same context as its lexical environment (the context of the function’s surroundings at the time of its creation).</p><p><a href="https://medium.com/@sergio.valverde.b/context-and-scope-in-javascript-and-other-related-concepts-aba408e34d2e">I wrote a separate article</a> explaining in more detail how the context of regular functions in general can change depending on how they are created and called, check that out for a more detailed explanation. In this article, I will focus on the peculiarities of arrow functions.</p><p>One example that I covered in the previous article was this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*cKJZmWolyOTnsfBn." /><figcaption><em>Note: A method inside a constructor is usually not a good idea, see why below.</em></figcaption></figure><p>In this example, we define an arrow function assigned to the property logThis of any instance created by the constructor function Test(). <strong>The point of the example was to show that the context of the arrow function will remain being the instance “test”, even when using it as a callback for the click event</strong>, but there are several reasons why doing this is not really a good idea.</p><p>Since we are no longer working with events and buttons, we can refactor it to make it a bit simpler to understand, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*V795NswVpTuZ5Lsw." /><figcaption><em>In this version of the example, the function we are testing just returns the “this” value.</em></figcaption></figure><p>This is a bit beside the topic for this article, but it’s important to clarify that declaring functions inside a constructor is usually not ideal and not a common practice, due to how constructors functions work in JavaScript. If you want to use prototypal object orientation and use constructor functions like these, it is better to define methods as a property of the prototype of the constructor, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*lO6RPqPe2x3NZddd." /><figcaption><em>Notice that the variable “thisValue” on line 12 evaluates to the instance with name “The new instance”</em></figcaption></figure><p>This is because the constructor function’s prototype will be used as the prototype for any instances created, they will all share the same prototype object. Therefore, the prototype’s methods are only created once, and they are shared by all the instances created with that constructor. If you define a method directly inside the constructor function, JavaScript will create a copy of the function for each new instance, and this is in most cases unneeded duplication.</p><p>Now just out of curiosity, let’s see what happens if we try to use arrow functions to define prototype methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*CWQOf4E6dVUMLtmR." /><figcaption><em>Same example as before, but returnThis is now an arrow function. Note how “thisValue” is now different. You cannot see it clearly in the information displayed by the inline evaluation, but the context becomes the global context (window object in browsers).</em></figcaption></figure><p>It breaks! As you can see, the context of the function no longer references the instance. This is definitely not what we wanted. Before getting into the details of why this scenario doesn’t work at all, it is better to see the same behavior with a simpler example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*llGxmsKZbQFprLAd." /><figcaption><em>Chewbarka Example #1: Here we have a dog with a bark method, which is defined as a regular function, and works as expected when executed on line 9 (it prints “woof!!”, the inline evaluator shows the result directly on line 6).</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*uLXJM7DlK33A3mX5." /><figcaption><em>Chewbarka Example #2: Same as above, but this time bark is defined as an arrow function. Note that when called it prints “undefined!!”, because the context is no longer the instance, so it cannot find a property “sound”.</em></figcaption></figure><p>In the previous article, I explained that scope and context are two different things. The context refers to a special object within which any function is considered to run, referenced by “this”, while scope relates to the accessibility of variables and their lifetime. However, to explain why the context for arrow functions behaves the way it does, we need to go back to the topic of scope for a bit.</p><p>In programming in general, there are two types of scoping: Lexical scoping and dynamic scoping. Lexical scoping means determining the scope of variables according to the code structure (a.k.a lexical structure) at compilation time, before it’s executed. Then when the code runs, the scope for all variables is already determined. In dynamic scope variables can end up being scoped in a different way, because it determines this scope at runtime. This depends on how the variables are being used, and which variables the stack holds at any given time.</p><p><strong><em>Javascript uses lexical scope:</em></strong> If you define a function inside another function, the inner function will always have access to any variables defined in the outer function’s scope, regardless of how the inner function is executed (which would be runtime). This is exactly how closures work.</p><p><em>(Side note: Even though Javascript is an interpreted language, it still goes through a “compilation” phase where it interprets all the code before running it)</em></p><p><strong>Interestingly, the behavior of a regular (not arrow) function’s context (the this object) in JavaScript works in a similar way to dynamic scope: The context is defined at runtime, depending on how the function is called. </strong>This is a critical difference between context and scope in Javascript.</p><p>Going back to arrow functions, the reason why their context behaves differently from regular functions is because it is calculated in a lexical fashion at compilation, instead of being dynamic at runtime. Hence, it doesn’t matter how they are called, they’ll just retain the context that was determined lexically.</p><p>In our Chewbarka example #1, the bark function’s context is determined when it runs: It is <strong>executed as a property</strong> of Chewbarka, and that’s why “this” points to Chewbarka. If we defined another variable “test” referencing exactly the same function, but calling it as a stand alone function, then it would no longer work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*ja86LuzRqmry5bWp." /><figcaption><em>test is a reference to the same bark function, but their context is different since it’s called differently.</em></figcaption></figure><p>In our Chewbarka example #2, since bark is now an arrow function, it doesn’t matter how it is called, and the context is set to be whatever the context was at this part of the application when this code was interpreted. Intuitively we might think that it would refer to the object literal where it is being declared, but this is a mistake.</p><p>Creating an object literal with properties and methods is really equivalent to creating an empty object literal and specifying the properties afterwards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/0*1fR_OO8B_0_ktfD8." /></figure><p>Following the same guidelines <a href="https://medium.com/@sergio.valverde.b/context-and-scope-in-javascript-and-other-related-concepts-aba408e34d2e#dab3">that I mentioned here</a> to determine what is the value for “this” at any given point in the code, in this example we are not inside any function, so “this” points to the global context. This is why the context for the arrow function bark is permanently bound to this global context. When we tried to use arrow functions to define prototype methods, the same thing happened.</p><p>As a conclusion therefore, it is not really recommended to use arrow functions to declare methods for objects. The only case where they do work as methods is if you use them directly inside a constructor function, but as mentioned, in general a constructor shouldn’t include methods. The lexical nature of the context of arrow functions is much more well suited for other use cases, like using them as helper functions, or as event callbacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3087a0d7b71f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/the-strange-case-of-arrow-functions-and-mr-3087a0d7b71f">The Strange Case of Arrow Functions and Mr.</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context and Scope in JavaScript, and Other Related Concepts]]></title>
            <link>https://medium.com/@sergio.valverde.b/context-and-scope-in-javascript-and-other-related-concepts-aba408e34d2e?source=rss-d3c983f58e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba408e34d2e</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sergio Valverde]]></dc:creator>
            <pubDate>Mon, 18 Dec 2017 19:20:08 GMT</pubDate>
            <atom:updated>2017-12-18T19:20:08.218Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I intend this article to be part of a series, where I write about fundamental web development topics that are critical for a well-rounded knowledge of front end web development. Although sometimes simple, these are concepts that must be well understood in order to really be proficient as a JavaScript developer.</em></p><p>As a JavaScript developer, can you clearly explain the difference between context and scope? What about hoisting, closures, and the possible different values for “this”?</p><p>Two terms in JavaScript development that are often confused with each other are context and scope. They are also part of the fundamentals of the language, that any serious JavaScript developer should seek to understand.</p><p><strong>Basically, scope refers to the visibility of variables; it defines in what parts of the application they can be accessed, depending on where they were defined. Context, on the other hand, relates to the object within which a function is called, and is referenced by the “this” keyword. </strong>The value that “this” references (a.k.a, the context) changes depending on how a function is called. We’ll cover both topics and some other important related concepts in this article.</p><p><strong>Scope</strong></p><p>As mentioned before, scope refers to the accessibility of variables from different parts of a JavaScript application. <strong>JavaScript has function scope (at least pre-ES6, see more below)</strong>, meaning that any variables declared inside a function will be available inside that function, but not outside of it. Also any child functions declared inside of the external function will have access to the variables from the parent function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/0*2QEgqewb2CJI45iq." /><figcaption><em>In this and the following examples I use an immediately invoked function. Here the variable x is scoped to just the function: it is undefined outside of it. </em><strong><em>Note: For all examples I use an inline evaluation tool called Quokka, which evaluates the code right on the editor</em></strong><em>.</em></figcaption></figure><p>JavaScript&#39;s function scope is in contrast with other programming languages, which have block scope. A block is defined by a pair of curly braces { } , and having block scope allows you to create temporary variables inside structures like <em>if</em> or <em>for</em> loops, which will be inaccessible from outside this block.</p><p>This was not the case in JavaScript: <strong>When you declare a variable with the “var” keyword, it will be scoped to the whole function where it’s defined</strong>, regardless of whether it was declared inside any kind of block structure. If you don’t properly understand this, it can lead to bugs where variables that were meant to be used only inside a block are available outside of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*RyehqQQy5vNKJ0LJ." /><figcaption><em>Notice how here the variable i is still defined after the block where it was defined, and it holds the value 10, because its scope is the whole function, not just the “for” block.</em></figcaption></figure><p>A variable declared using <em>var</em> will be available anywhere inside that function, even in lines before the actual declaration (but still inside the same function). This happens because of a feature called <strong>hoisting</strong>, which means that the variable declaration is moved to the top of the scope (the function where it was declared). Only the declaration is moved, the assignment stays in place.</p><p><strong>CAUTION! If you forget to declare a variable using var, it will be declared as a global variable! </strong>Javascript will look for the declaration up the function chain, to see if the declaration was in an outer function, finally reaching the global scope and declaring the variable in the global scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/0*ArMw0KYHKhKFhv6X." /><figcaption><em>This example is the same as the first one, but without the var keyword. The x variable is still available after the function because x was hoisted to the global scope.</em></figcaption></figure><p>Starting from the sixth version of ECMAScript (the official specification for the JavaScript language), published in 2015, the language now includes two new keywords to declare variables: <strong>let and const, which are block-scoped instead of function-scoped</strong>. In general, it is recommended to use let instead of var, since they work the same except for the scope, and having block scope for variables is less error prone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*MWjbRGdLXboFWnqJ." /><figcaption><em>This is the same as the previous “for” loop example, but now using let instead of var. Note how the i variable is only defined inside the block now.</em></figcaption></figure><p>Const is a bit special, because variables (or should we say, constants) declared with the const keyword cannot be reassigned. If you declare a const and assign it a primitive type (a number, a string, a boolean, null or undefined), this value cannot be changed in any way. If you declare a const that references an object however, it doesn’t cause complete immutability, because the properties of the object can still be changed, but you are prevented from reassigning another object to that constant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*IaB7MaWptUpHTo8c." /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/0*gmUbnbZSwAy2BQ29." /><figcaption><em>In these two examples, the first one throws an error because we are trying to reassign a const variable. The second one doesn’t throw an error, because we are only modifying a property of the const object, we are not actually reassigning the object it references.</em></figcaption></figure><p>Again, it is recommended to always use const over let and var whenever you can, which is actually in most cases. <strong>Using const variables is a good practice because it minimizes mutable state</strong>: It minimizes the amount of variables that can change inside of the logic of an application. The more moving parts (for example, the internal state that can be modified) that a piece of software has, the more likely it is to have unexpected bugs. If you declare a variable as a const, you can have the confidence that it will not be changed later on in the program. This is also beneficial in terms of readability and maintainability, because if another programmer or even you have to go back to the code in the future, it will be clear that the intention of that const variable was to remain constant.</p><p><strong>Closures</strong></p><p>Closures are also a fundamental aspect of the topic of scope in Javascript, that must be understood well. There are a lot of good resources explaining closures, like <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">Eric Elliott’s article “Master the JavaScript Interview: What is a Closure?”</a>. I recommend reading his article for a more detailed explanation. He defines closures as:</p><blockquote>“A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).”</blockquote><p>This means that when you have an inner function inside another function, the inner function will have access to the scope of the outer function, including the arguments received by the outer function, and will continue to have access even after the outer function has executed and returned.</p><p>Closures in JavaScript are important to implement design patterns such as the module pattern or revealing module pattern, which provide data privacy to objects and functions. This article will not go into details of design patterns, but basically closures make this possible because the inner functions can have access to a scope that will be completely inaccessible to anything else. Closures are also used for functional programming techniques like currying and partial application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*oUYh-wK65mJbvkxL." /><figcaption><em>Here, greeter is assigned the return value of the immediately invoked function, which is an object with a sayHi method. This method has access to the variable greeting, even after the outer function finished executing.</em></figcaption></figure><p><strong>Context</strong></p><p>Context in JavaScript doesn’t refer at all to variables and their visibility, <strong>context refers to the object within which a function is executed, and it’s referenced by the “this” keyword</strong>, which allows you to access its properties or methods. Depending on how a function is called, there are six possible scenarios, where “this” will take different values:</p><ol><li>Outside of any function: If the keyword “this” is used outside of any function, it will refer to the global context. In browsers, it would reference the window object.</li><li>Inside a constructor function: When a function is called as a constructor, using the new keyword, then any usage of “this” inside of the function will refer to the new object instance that will be created. In this way constructors can add properties and methods that will belong to the new instance (not including adding shared methods to the constructor’s prototype, but that is another topic).</li><li>Inside an object method: An object method is a function that is a property on an object. In this case, “this” will be a reference to that object. This is very often used to access and modify other properties or methods of the object.</li><li>Inside a simple function: This means a function that is just declared as a “stand-alone” function, without being a property of any object, and without calling it as a constructor with new. In these cases, “this” will reference the global context (window object in browsers).</li><li>Inside a function that is called as a callback for an event listener: <strong>Regardless of where and how a function is defined, if it is called as a callback for an event listener (for example, to be called when a click event is triggered), “this” inside that function will reference the target element of the event (not counting arrow functions)</strong>. This is a very common situation in JavaScript, and a frequent source of errors, because the “this” value that would probably make more sense to a developer is overridden by the target element of the event. There are several ways to get around this issue, that I’ll mention below.</li><li>Inside an arrow function: In ES6 arrow functions were introduced, and not only do they provide a more concise syntax for writing functions, but they also have the peculiarity that they will retain the same context as its lexical environment (the context of the function&#39;s surroundings at the time of its creation), no matter how they are called later. Using arrow functions is actually one of the ways to deal with the issue of event handlers changing the context of callback functions.</li></ol><p><strong>Bind, Call, Apply, and other ways to manually specify context</strong></p><p>Now that we saw how context is normally determined, it’s also important to mention some techniques that can be used to have more control on the context of a function.</p><ul><li>Arrow Functions: Even though arrow functions can really be considered as one of the six common scenarios that determine context, it is anyways worth noting again that they are a useful technique to use when you want to prevent the context of a function from being changed, such as when calling a function as a callback for an event handler. This way, you know that the function will have the same context from where it was defined.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*Ct6YNwJo8AOSrR-F." /><figcaption><em>In this example, we create a new test instance from a constructor function. Since the context inside constructor functions is the new instance, we would expect the method logThis() to log the instance, but since we are calling it as a callback to a click event on a button, “this” becomes the button.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*0vt7CfEIddKm2Z-f." /><figcaption><em>However, note what happens if we just change the declaration of logThis to be an arrow function: Even when using it as an event callback, it will correctly print to the console the instance created. This happens because the arrow function’s context will be permanently set to the context of its surroundings at the time of the function’s creation.</em></figcaption></figure><ul><li>Bind: The function bind is available as a method of any JavaScript function (thanks to prototypal inheritance, since bind is a method of Function.prototype). When calling bind on a function, it will return a new version of the function, that will have the context permanently set to whatever object bind receives as its first argument. Bind can also optionally receive more arguments, which will then always be used as arguments for the target function whenever it’s called. This new function can then be safely used as an event handler’s callback, knowing that the context will remain fixed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*1bgX7AreCUkrgmEs." /><figcaption><em>In this version of the same example, we are back to using a regular function for logThis, which would print the button element instead of the instance when clicking on the button. However, we are preventing this here by using a callback for the click event that is bound to the test instance, therefore its context will not be changed.</em></figcaption></figure><ul><li>Call: This function is similar to bind, and can also be called on any function. The difference is that call doesn’t return a new version of the target function, it just immediately executes the target function while setting its context to be the object that call() received as an argument. As with bind, call can also receive extra optional parameters, that will be passed as parameters for calling the target function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*Yav4JgzKZN01Juxd." /><figcaption><em>In this example we create two dogs, Rufus and Duke, and then we call the method getName of Rufus on line 11. As expected, it returns “Rufus”. However, if we then call the same method of Rufus with .call(Duke), it will treat Duke as its context, overriding the normal context, even though it still is a method that belongs to Rufus.</em></figcaption></figure><ul><li>Apply: Apply works exactly the same as call, except that the optional parameters should not be passed individually, but as an array of values. For our purposes, it would be used in the same way as the previous example for call().</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba408e34d2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>