<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Lydia Hallie</title>
    <description>The latest articles on DEV Community by Lydia Hallie (@lydiahallie).</description>
    <link>https://dev.to/lydiahallie</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F198900%2Fd19268b1-6b0b-4530-9889-64fcf0a19d6d.png</url>
      <title>DEV Community: Lydia Hallie</title>
      <link>https://dev.to/lydiahallie</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/lydiahallie"/>
    <language>en</language>
    <item>
      <title>✋🏼🔥 CS Visualized: CORS</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Mon, 27 Jul 2020 14:55:58 +0000</pubDate>
      <link>https://dev.to/lydiahallie/cs-visualized-cors-5b8h</link>
      <guid>https://dev.to/lydiahallie/cs-visualized-cors-5b8h</guid>
      <description>&lt;p&gt;It’s every developer’s frustration once in a while to see that big red &lt;code&gt;Access to fetched has been blocked by CORS policy&lt;/code&gt; error in your console! 😬 Although there are some ways to quickly get rid of this error, let’s not take anything for granted today! Instead, let’s see what CORS is actually doing, and why it’s actually our friend 👏🏼&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;❗️ In this blog post I won’t explain HTTP basics. In case you’d like to know more about HTTP requests and responses, I wrote &lt;a href="https://www.lydiahallie.dev/blog/http11" rel="noopener noreferrer"&gt; a small blog post&lt;/a&gt; about it a while ago though 🙂 In my examples I use HTTP/1.1 instead of HTTP/2, this doesn’t affect CORS.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;

&lt;tr&gt;&lt;td&gt;S H O R T C U T S&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;
    &lt;th&gt;✋🏼 Same-Origin Policy
&lt;/th&gt;
  &lt;/tr&gt;
&lt;tr&gt;
    &lt;th&gt;🔥 Client-side CORS
  &lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;th&gt;💻 Server-side CORS
&lt;/th&gt;
  &lt;/tr&gt;
&lt;tr&gt;
    &lt;th&gt;🚀 Preflight Requests &lt;/th&gt;
  &lt;/tr&gt;
&lt;tr&gt;
    &lt;th&gt;🍪 &lt;a href="credentials"&gt;Credentials&lt;/a&gt;
&lt;/th&gt;
  &lt;/tr&gt;

&lt;/table&gt;&lt;/div&gt;
    




&lt;p&gt;On the frontend, we often want to display data that's located elsewhere! Before we can display this data, the browser first has to make a request to a server in order to fetch that data! The client sends an HTTP request with all the information that the server needs in order to send that data back to the client 🙂&lt;/p&gt;

&lt;p&gt;Let’s say we’re trying to fetch some user information on our  &lt;code&gt;www.mywebsite.com&lt;/code&gt; website from a server that’s located at &lt;code&gt;api.website.com&lt;/code&gt;!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fqyeikeonofi8dfl0jz2t.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fqyeikeonofi8dfl0jz2t.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Perfect! 😃 We just sent an HTTP request to the server, which then responded with the JSON data we asked for. &lt;/p&gt;

&lt;p&gt;Let's try the &lt;em&gt;exact same&lt;/em&gt; request but from &lt;strong&gt;another domain&lt;/strong&gt;. Instead of making the request from &lt;code&gt;www.mywebsite.com&lt;/code&gt;, we’re now making the request from a website located at &lt;code&gt;www.anotherdomain.com&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flxhuh29biuwhefs3k9d9.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flxhuh29biuwhefs3k9d9.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Wait, what? We sent the exact same request, but this time the browser shows us a weird error?&lt;/p&gt;

&lt;p&gt;We just saw CORS in action! 💪🏼 Let’s see why this error occurred, and what it exactly means. &lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt; ✋🏼 Same-Origin Policy
&lt;/h2&gt;

&lt;p&gt;The web enforces something called the &lt;strong&gt;same-origin policy&lt;/strong&gt;.  By default, we can only access resources that are located at the &lt;strong&gt;same origin&lt;/strong&gt; as the origin of our request! 💪🏼 It's totally okay to load an image that's located at &lt;code&gt;https://mywebsite.com/image1.png&lt;/code&gt;, for example.&lt;/p&gt;

&lt;p&gt;A resource is cross-origin when it's located at a different (sub)domain, protocol, or port!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fibyoyo1yqta9cdvh0tbv.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fibyoyo1yqta9cdvh0tbv.jpeg" alt="image3"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cool, but why does the same-origin policy even exist? &lt;/p&gt;

&lt;p&gt;Let's say that the same-origin policy didn't exist, and you accidentally clicked one of the many virus links your aunt sent you on Facebook. This link redirects you to an "evil website" that has an iframe embedded which loads your bank's website, and successfully logs you in by some set cookies! 😬 &lt;/p&gt;

&lt;p&gt;The developers of this "evil website" made it possible for the website to access this iframe and interact with the DOM contents of your bank's website in order to send money to their account on your behalf! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F50nmgrnkf6pb6gphno06.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F50nmgrnkf6pb6gphno06.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yeah... this is a huge security risk! We don't want anyone to just be able to access everything 😧&lt;/p&gt;

&lt;p&gt;Luckily, the same-origin policy helps us out here! This policy makes sure that we can only access resources from the &lt;strong&gt;same origin&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F8unei9l9enunbpr58o54.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F8unei9l9enunbpr58o54.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case, the origin &lt;code&gt;www.evilwebsite.com&lt;/code&gt; tried to access cross-origin resources from &lt;code&gt;www.bank.com&lt;/code&gt;! The same-origin policy blocked this from happening and made sure that the evil website's devs couldn't just access our bank data 🥳&lt;/p&gt;

&lt;p&gt;Okay, so... what does this have to do with CORS? &lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt; 🔥 Client-side CORS
&lt;/h2&gt;

&lt;p&gt;Although the same-origin policy actually only applies to scripts, browsers "extended" this policy for JavaScript requests: by default, we can only access fetched resources from the &lt;strong&gt;same origin&lt;/strong&gt;!  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F0qe4yzasvrm7r0a76kui.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F0qe4yzasvrm7r0a76kui.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hmm, but... We often have to access cross-origin resources 🤔 Maybe our frontend needs to interact with our backend API in order to load the data?  In order to allow cross-origin requests safely, the browser uses a mechanism called &lt;strong&gt;CORS&lt;/strong&gt;! 🥳 &lt;/p&gt;

&lt;p&gt;CORS stands for &lt;strong&gt;Cross-Origin Resource Sharing&lt;/strong&gt;. Although the browser disallows us from accessing resources that aren’t located at the same origin, we can use CORS to change those security restrictions a bit while still making sure that we’re accessing those resources safely 🎉 &lt;/p&gt;

&lt;p&gt;User agents (a browser, for example) can use the CORS mechanism in order to &lt;strong&gt;allow cross-origin requests&lt;/strong&gt; which otherwise would've been blocked, based on the values of certain CORS-specific headers in the HTTP response! ✅ &lt;/p&gt;

&lt;p&gt;When a cross-origin request is made, the client automatically adds an extra header to our HTTP request: &lt;code&gt;Origin&lt;/code&gt;. The value of the &lt;code&gt;Origin&lt;/code&gt; header is the origin where the request came from! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F91qh9mo3q5lcl0ng4t0r.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F91qh9mo3q5lcl0ng4t0r.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In order for the browser to allow accessing cross-origin resources, it expects certain headers from the server's response, which specify whether this server allows cross-origin requests! &lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt; 💻 Server-side CORS
&lt;/h2&gt;

&lt;p&gt;As a server developer, we can make sure that cross-origin requests are allowed by adding extra headers to the HTTP response, which all start with &lt;code&gt;Access-Control-*&lt;/code&gt; 🔥 Based on the values of these CORS response headers, the browser can now allow certain cross-origin responses which would’ve normally been blocked by the same-origin policy!  &lt;/p&gt;

&lt;p&gt;Although there are &lt;a href="https://fetch.spec.whatwg.org/#http-responses" rel="noopener noreferrer"&gt;several CORS headers&lt;/a&gt; we can use, there is one header that the browser needs in order to allow cross-origin resource access:  &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt;! 🙂 &lt;br&gt;
The value of this header specifies &lt;strong&gt;which origins are allowed to access the resources&lt;/strong&gt; that they're requesting from the server. &lt;/p&gt;

&lt;p&gt;If we’re developing a server that &lt;code&gt;https://mywebsite.com&lt;/code&gt; should have access to, we can add the value of that domain to the &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; header!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbpw6vwe6w5tm3cadqg7j.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbpw6vwe6w5tm3cadqg7j.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Awesome! 🎉 This header is now added to the response that the server sends back to the client. By adding this header, the &lt;strong&gt;same-policy origin will no longer restrict us from receiving resources&lt;/strong&gt; that were located at the &lt;code&gt;https://api.mywebsite.com&lt;/code&gt; origin, if we sent the request from &lt;code&gt;https://mywebsite.com&lt;/code&gt;! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fakf0epavr00o2vo857lc.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fakf0epavr00o2vo857lc.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The CORS mechanism within the browser checks whether the value of the &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; header equals the value of the &lt;code&gt;Origin&lt;/code&gt; that was sent by the request 🤚🏼 &lt;/p&gt;

&lt;p&gt;In this case, the origin of our request is &lt;code&gt;https://www.mywebsite.com&lt;/code&gt;, which is listed in the &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; response header! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ffoathske6a5prjf02dyf.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ffoathske6a5prjf02dyf.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Perfect! 🎉 We were able to receive the cross-origin resources successfully!  So what happens when we’re trying to access these resources from an origin that’s not listed in the &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; header? 🤔&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flqtoobekf1h1d08lcl56.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flqtoobekf1h1d08lcl56.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ahh yeah, CORS throws the notorious error that can be so frustrating at times! But now we actually see that it makes total sense&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

The 'Access-Control-Allow-Origin' header has a value
 'https://www.mywebsite.com' that is not equal 
to the supplied origin. 


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this case, the supplied origin was &lt;code&gt;https://www.anotherwebsite.com&lt;/code&gt;. However, the server didn’t have this supplied origin in the list of allowed origins in the &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; header! CORS successfully blocked the request, and we cannot access the fetched data in our code 😃&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;CORS also allows us to add the wildcard &lt;code&gt;*&lt;/code&gt; as the value for the allowed origins. This means that requests from &lt;em&gt;all origins&lt;/em&gt; should have access to the requested resources, so be careful! &lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; is one of the many CORS headers we can provide. A server developer can extend the server's CORS policies in order to (dis)allow certain requests! 💪🏼&lt;/p&gt;

&lt;p&gt;Another common header is the &lt;code&gt;Access-Control-Allow-Methods&lt;/code&gt; header! CORS will only allow cross-origin requests if they were sent with the listed methods.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyjjhg7yr3kjrh1nm44mo.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyjjhg7yr3kjrh1nm44mo.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case, only requests with a &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;POST&lt;/code&gt;, or &lt;code&gt;PUT&lt;/code&gt; method will be allowed! Other methods such as &lt;code&gt;PATCH&lt;/code&gt; or &lt;code&gt;DELETE&lt;/code&gt; will be blocked ❌&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you're curious about what the other possible CORS headers are and what they're used for, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#The_HTTP_response_headers" rel="noopener noreferrer"&gt;check out this list&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Speaking of &lt;code&gt;PUT&lt;/code&gt;, &lt;code&gt;PATCH&lt;/code&gt;, and &lt;code&gt;DELETE&lt;/code&gt; requests, CORS actually handles those requests differently! 🙃 These "&lt;em&gt;non-simple&lt;/em&gt;" requests initiate something called a &lt;strong&gt;preflight request&lt;/strong&gt;! &lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt; 🚀 Preflighted Requests
&lt;/h2&gt;

&lt;p&gt;CORS has two types of requests: a &lt;strong&gt;simple request&lt;/strong&gt; and a &lt;strong&gt;preflighted request&lt;/strong&gt;. Whether a request is simple or preflighted depends on some values within the request (don't worry, you don't have to memorize this lol).&lt;/p&gt;

&lt;p&gt;A request is simple when the request is a &lt;code&gt;GET&lt;/code&gt; or &lt;code&gt;POST&lt;/code&gt; method and doesn't have any custom headers! Any other request, such as requests with a &lt;code&gt;PUT&lt;/code&gt;, &lt;code&gt;PATCH&lt;/code&gt;, or &lt;code&gt;DELETE&lt;/code&gt; method, will be preflighted. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In case you’re just curious about which requirements a request has to meet in order to be a simple request, MDN has &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests" rel="noopener noreferrer"&gt;a useful list&lt;/a&gt;! &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Okay sure, but what does "preflighted request" even mean, and why does this happen?&lt;/p&gt;




&lt;p&gt;Before the actual request gets sent, the client generates a preflighted request! The preflighted request contains information about the actual request we’re about to in its &lt;code&gt;Access-Control-Request-*&lt;/code&gt; headers 🔥 &lt;/p&gt;

&lt;p&gt;This gives the server information about the actual request that the browser is trying to make: what is the &lt;strong&gt;method&lt;/strong&gt; of the request, what are the &lt;strong&gt;additional headers&lt;/strong&gt;, and so on.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fpp30p7ej496f8bqta4he.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fpp30p7ej496f8bqta4he.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The server receives this preflighted request, and sends an empty HTTP response back with the server's CORS headers! The browser receives the preflight response, which contains no data besides the CORS headers, and checks whether the HTTP request should be allowed! ✅&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fpy19auar8xhs933ilmsc.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fpy19auar8xhs933ilmsc.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If that's the case, the browser sends the actual request to the server, which then responds with the data we asked for!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fpfv1dcg77yjxbue5ryzf.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fpfv1dcg77yjxbue5ryzf.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, if it’s not the case, CORS will block the preflighted request, and the actual request never gets sent ✋🏼 The preflighted request is a great way to prevent us from accessing or modifying resources on servers that don't have any CORS policies enabled (yet)! Servers are now protected from potentially unwanted cross-origin requests 😃&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;💡 In order to reduce the number of roundtrips to our server, we can cache the preflighted responses by adding an &lt;code&gt;Access-Control-Max-Age&lt;/code&gt; header to our CORS requests! We can cache the preflighted response this way, which the browser can use instead of sending a new preflighted request!&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  🍪 &lt;a&gt;&lt;/a&gt;Credentials
&lt;/h2&gt;

&lt;p&gt;Cookies, authorization headers, and TLS certificates are by default only set on same-origin requests! However, we may want to use these credentials in our cross-origin request. Maybe we want to include cookies on the request that the server can use in order to identify the user! &lt;/p&gt;

&lt;p&gt;Although CORS doesn't include credentials by default, we can change this by adding the &lt;code&gt;Access-Control-Allow-Credentials&lt;/code&gt; CORS header!   🎉&lt;/p&gt;

&lt;p&gt;If we want to include cookies and other authorization headers to our cross-origin request, we need to set the &lt;code&gt;withCredentials&lt;/code&gt; field to &lt;code&gt;true&lt;/code&gt; on the request and add the &lt;code&gt;Access-Control-Allow-Credentials&lt;/code&gt; header to the response. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fvg3yo6qfqw12oh0f68yg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fvg3yo6qfqw12oh0f68yg.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;All set! We can now include credentials in our cross-origin request 🥳&lt;/p&gt;




&lt;p&gt;Although I think we can all agree that CORS errors can be frustrating at times, it's amazing that it enables us to safely make cross-origin requests in the browser (it should receive a bit more love lol) ✨ &lt;/p&gt;

&lt;p&gt;Obviously there is so much more to the same-origin policy and CORS than I was able to cover here in this blog post! Luckily, there are many great resources out there like &lt;a href="https://livebook.manning.com/book/cors-in-action/part-1/" rel="noopener noreferrer"&gt;this one&lt;/a&gt; or &lt;a href="https://www.w3.org/wiki/CORS_Enabled" rel="noopener noreferrer"&gt;the W3 spec&lt;/a&gt; if you want to read more about it 💪🏼 &lt;/p&gt;

&lt;p&gt;And as always, feel free to reach out to me! 😊&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
 &lt;td&gt;✨ &lt;a href="https://www.twitter.com/lydiahallie" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;👩🏽‍💻 &lt;a href="https://www.instagram.com/theavocoder" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💻 &lt;a href="https://www.github.com/lydiahallie" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💡 &lt;a href="https://www.linkedin.com/in/lydia-hallie" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;📷 &lt;a href="https://www.youtube.com/channel/UC4EWKIKdKiDtAscQ9BIXwUw" rel="noopener noreferrer"&gt;YouTube&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💌 &lt;a href="mailto:lydiahallie.dev@gmail.com%22"&gt;Email&lt;/a&gt;
&lt;/td&gt;

&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

</description>
      <category>tutorial</category>
      <category>webdev</category>
      <category>security</category>
    </item>
    <item>
      <title>⭐️🎀 JavaScript Visualized: Promises &amp; Async/Await</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Tue, 14 Apr 2020 16:46:40 +0000</pubDate>
      <link>https://dev.to/lydiahallie/javascript-visualized-promises-async-await-5gke</link>
      <guid>https://dev.to/lydiahallie/javascript-visualized-promises-async-await-5gke</guid>
      <description>&lt;p&gt;If you're here in 2024 (or later), here's an updated video:&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/Xs1EMmBLpn4"&gt;
&lt;/iframe&gt;
&lt;/p&gt;




&lt;p&gt;Ever had to deal with JS code that just... didn't run the way you expected it to? Maybe it seemed like functions got executed at random, unpredictable times, or the execution got delayed. There's a chance you were dealing with a cool new feature that ES6 introduced: &lt;strong&gt;Promises&lt;/strong&gt;! &lt;/p&gt;

&lt;p&gt;My curiosity from many years ago has paid off and my sleepless nights have once again given me the time to make some animations. Time to talk about Promises: &lt;strong&gt;why&lt;/strong&gt; would you use them, &lt;strong&gt;how&lt;/strong&gt; do they work "under the hood", and how can we write them in the most &lt;strong&gt;modern&lt;/strong&gt; way?&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you haven't read my previous post on the JavaScript Event Loop yet, it may be useful to read that first! I'll be covering the event loop again assuming some basic knowledge about the call stack, Web API and the queue, but this time we'll also be covering some exciting extra features 🤩 &lt;/p&gt;
&lt;div class="ltag__link"&gt;
  &lt;a href="/lydiahallie" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F198900%2Fd19268b1-6b0b-4530-9889-64fcf0a19d6d.png" alt="lydiahallie"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/lydiahallie/javascript-visualized-event-loop-3dif" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;✨♻️ JavaScript Visualized: Event Loop&lt;/h2&gt;
      &lt;h3&gt;Lydia Hallie ・ Nov 20 '19&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#javascript&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#webdev&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;

&lt;/blockquote&gt;




&lt;p&gt;If you're already somewhat familiar with promises, here are some shortcuts to save you some precious scrolling time.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
    &lt;tr&gt;
     &lt;td&gt;
      🥳 Introduction
     &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt; &lt;td&gt;
      ⚡️ Promise Syntax
&lt;/td&gt;
    &lt;/tr&gt;
      &lt;tr&gt;
&lt;td&gt;
         ♻️ Event Loop: Microtasks and (Macro)tasks
&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
&lt;td&gt;
        🚀 Async/Await
&lt;/td&gt;
      &lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;







&lt;h3&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Introduction
&lt;/h3&gt;

&lt;p&gt;When writing JavaScript, we often have to deal with tasks that rely on other tasks! Let's say that we want to get an image, compress it, apply a filter, and save it 📸&lt;/p&gt;

&lt;p&gt;The very first thing we need to do, is &lt;em&gt;get&lt;/em&gt; the image that we want to edit. A &lt;code&gt;getImage&lt;/code&gt; function can take care of this! Only once that image has been loaded successfully, we can pass that value to a &lt;code&gt;resizeImage&lt;/code&gt; function. When the image has been resized successfully, we want to apply a filter to the image in the &lt;code&gt;applyFilter&lt;/code&gt; function. After the image has been compressed and we've added a filter, we want to save the image and let the user know that everything worked correctly! 🥳&lt;/p&gt;

&lt;p&gt;In the end, we'll end up with something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fixceqsql5hpdq8txx43s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fixceqsql5hpdq8txx43s.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hmm... Notice anything here? Although it's... &lt;em&gt;fine&lt;/em&gt;, it's not great. We end up with many nested callback functions that are dependent on the previous callback function. This is often referred to as a &lt;a href="http://callbackhell.com/" rel="noopener noreferrer"&gt;&lt;em&gt;callback hell&lt;/em&gt;&lt;/a&gt;, as we end up with tons of nested callback functions that make the code quite difficult to read! &lt;/p&gt;

&lt;p&gt;Luckily, we now got something called &lt;strong&gt;promises&lt;/strong&gt; to help us out! Let's take a look at what promises are, and how they can help us in situations like these! 😃&lt;/p&gt;




&lt;h3&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Promise Syntax
&lt;/h3&gt;

&lt;p&gt;ES6 introduced &lt;strong&gt;Promises&lt;/strong&gt;. In many tutorials, you'll read something like:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"A promise is a placeholder for a value that can either resolve or reject at some time in the future"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Yeah... That explanation never made things clearer for me. In fact it only made me feel like a Promise was a weird, vague, unpredictable piece of magic. So let's look at what promises &lt;em&gt;really&lt;/em&gt; are.&lt;/p&gt;

&lt;p&gt;We can create a promise, using a &lt;code&gt;Promise&lt;/code&gt; constructor that receives a callback. Okay cool, let's try it out!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F79zi452hphe7ecylhozy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F79zi452hphe7ecylhozy.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Wait woah, what just got returned?&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;Promise&lt;/code&gt; is an object that contains a &lt;strong&gt;status&lt;/strong&gt;, (&lt;code&gt;[[PromiseStatus]]&lt;/code&gt;) and a &lt;strong&gt;value&lt;/strong&gt; (&lt;code&gt;[[PromiseValue]]&lt;/code&gt;). In the above example, you can see that the value of &lt;code&gt;[[PromiseStatus]]&lt;/code&gt; is &lt;code&gt;"pending"&lt;/code&gt;, and the value of the promise is &lt;code&gt;undefined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Don't worry - you'll never have to interact with this object, you can't even access the &lt;code&gt;[[PromiseStatus]]&lt;/code&gt; and &lt;code&gt;[[PromiseValue]]&lt;/code&gt; properties! However, the values of these properties are important when working with promises.&lt;/p&gt;




&lt;p&gt;The value of the &lt;code&gt;PromiseStatus&lt;/code&gt;, the &lt;strong&gt;state&lt;/strong&gt;, can be one of three values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;✅ &lt;code&gt;fulfilled&lt;/code&gt;: The promise has been &lt;code&gt;resolved&lt;/code&gt;. Everything went fine, no errors occurred within the promise 🥳&lt;/li&gt;
&lt;li&gt;❌ &lt;code&gt;rejected&lt;/code&gt; : The promise has been &lt;code&gt;rejected&lt;/code&gt;. Argh, something went wrong..&lt;/li&gt;
&lt;li&gt;⏳ &lt;code&gt;pending&lt;/code&gt;: The promise has neither resolved nor rejected (yet), the promise is still &lt;code&gt;pending&lt;/code&gt;. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Alright this all sounds great, but &lt;em&gt;when&lt;/em&gt; is a promise status &lt;code&gt;"pending"&lt;/code&gt;, &lt;code&gt;"fulfilled"&lt;/code&gt; or &lt;code&gt;"rejected"&lt;/code&gt;? And why does that status even matter?&lt;/p&gt;

&lt;p&gt;In the above example, we just passed the simple callback function &lt;code&gt;() =&amp;gt; {}&lt;/code&gt; to the &lt;code&gt;Promise&lt;/code&gt; constructor. However, this callback function actually receives two arguments. The value of the first argument, often called &lt;code&gt;resolve&lt;/code&gt; or &lt;code&gt;res&lt;/code&gt;, is the method to be called when the Promise should &lt;strong&gt;resolve&lt;/strong&gt;. The value of the second argument, often called &lt;code&gt;reject&lt;/code&gt; or &lt;code&gt;rej&lt;/code&gt;, is the value method to be called when the Promise should &lt;strong&gt;reject&lt;/strong&gt;, something went wrong.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fduen4peq0bdr55cka5ya.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fduen4peq0bdr55cka5ya.png"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Let's try and see that gets logged when we invoke either the &lt;code&gt;resolve&lt;/code&gt; or &lt;code&gt;reject&lt;/code&gt; method! In my example, I called the &lt;code&gt;resolve&lt;/code&gt; method &lt;code&gt;res&lt;/code&gt;, and the &lt;code&gt;reject&lt;/code&gt; method &lt;code&gt;rej&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fz0b9v0h7aiq073l5tl2l.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fz0b9v0h7aiq073l5tl2l.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Awesome! We finally know how to get rid of the &lt;code&gt;"pending"&lt;/code&gt; status and the &lt;code&gt;undefined&lt;/code&gt; value! The &lt;strong&gt;status&lt;/strong&gt; of a promise is &lt;code&gt;"fulfilled"&lt;/code&gt; if we invoked the &lt;code&gt;resolve&lt;/code&gt; method, and the status of the promise is &lt;code&gt;"rejected&lt;/code&gt;" if we invoked the &lt;code&gt;rejected&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;value&lt;/strong&gt; of a promise, the value of &lt;code&gt;[[PromiseValue]]&lt;/code&gt;, is the value that we pass to the either the &lt;code&gt;resolved&lt;/code&gt; or &lt;code&gt;rejected&lt;/code&gt; method as their argument.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Fun fact, I let Jake Archibald proofread this article and he actually pointed out there's a bug in Chrome that currently shows the status as &lt;code&gt;"resolved"&lt;/code&gt; instead of &lt;code&gt;"fulfilled"&lt;/code&gt;. Thanks to &lt;a href="https://twitter.com/mathias" rel="noopener noreferrer"&gt;Mathias Bynens&lt;/a&gt; it's now fixed in Canary! 🥳🕺🏼 &lt;iframe class="tweet-embed" id="tweet-1248179232775319559-992" src="https://platform.twitter.com/embed/Tweet.html?id=1248179232775319559"&gt;
&lt;/iframe&gt;

  // Detect dark theme
  var iframe = document.getElementById('tweet-1248179232775319559-992');
  if (document.body.className.includes('dark-theme')) {
    iframe.src = "https://platform.twitter.com/embed/Tweet.html?id=1248179232775319559&amp;amp;theme=dark"
  }



 &lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Okay so, now we know a little bit better how to control that vague &lt;code&gt;Promise&lt;/code&gt; object. But what is it used for?&lt;/p&gt;

&lt;p&gt;In the introductory section, I showed an example in which we get an image, compress it, apply a filer, and save it! Eventually, this ended up being a nested callback mess.&lt;/p&gt;

&lt;p&gt;Luckily, Promises can help us fix this! First, let's rewrite the entire code block, so that each function returns a &lt;code&gt;Promise&lt;/code&gt; instead.&lt;/p&gt;

&lt;p&gt;If the image is loaded and everything went fine, let's &lt;strong&gt;resolve&lt;/strong&gt; the promise with the loaded image! Else, if there was an error somewhere while loading the file, let's &lt;strong&gt;reject&lt;/strong&gt; the promise with the error that occurred.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fiebp0rzfnfqsrmmjplme.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fiebp0rzfnfqsrmmjplme.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's see what happens when we run this in the terminal!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwsu5nn26dp4elcwh764m.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwsu5nn26dp4elcwh764m.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cool! A promise got returned with the value of the parsed data, just like we expected.&lt;/p&gt;

&lt;p&gt;But... what now? We don't care about that entire promise object, we only care about the value of the data! Luckily, there are built-in methods to get a promise's value. To a promise, we can attach 3 methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;.then()&lt;/code&gt;: Gets called after a promise &lt;em&gt;resolved&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.catch()&lt;/code&gt;: Gets called after a promise &lt;em&gt;rejected&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.finally()&lt;/code&gt;: &lt;em&gt;Always&lt;/em&gt; gets called, whether the promise resolved or rejected.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fmu1aqqnyfjsfon5hwrtw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fmu1aqqnyfjsfon5hwrtw.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;.then&lt;/code&gt; method receives the value passed to the &lt;code&gt;resolve&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F11vxhn9cun7stpjbdi80.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F11vxhn9cun7stpjbdi80.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;.catch&lt;/code&gt; method receives the value passed to the &lt;code&gt;rejected&lt;/code&gt; method&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fv5y24jz4u89flazvdyn4.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fv5y24jz4u89flazvdyn4.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, we have the value that got resolved by the promise without having that entire promise object! We can now do whatever we want with this value.&lt;/p&gt;




&lt;p&gt;FYI, when you know that a promise will always resolve or always reject, you can write &lt;code&gt;Promise.resolve&lt;/code&gt; or &lt;code&gt;Promise.reject&lt;/code&gt; , with the value you want to reject or resolve the promise with!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F90hxwjfadzslvdbkr4l8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F90hxwjfadzslvdbkr4l8.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You'll often see this syntax in the following examples 😄&lt;/p&gt;




&lt;p&gt;In the &lt;code&gt;getImage&lt;/code&gt; example,  we ended up having to nest multiple callbacks in order to run them. Luckily, the &lt;code&gt;.then&lt;/code&gt; handlers can help us with that! 🥳&lt;/p&gt;

&lt;p&gt;The result of the &lt;code&gt;.then&lt;/code&gt; itself is a promise value. This means that we can chain as many &lt;code&gt;.then&lt;/code&gt;s as we want: the result of the previous &lt;code&gt;then&lt;/code&gt; callback will be passed as an argument to the next &lt;code&gt;then&lt;/code&gt; callback! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fi6busbetmoya9vny2eku.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fi6busbetmoya9vny2eku.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the case of the &lt;code&gt;getImage&lt;/code&gt; example, we can chain multiple &lt;code&gt;then&lt;/code&gt; callbacks in order to pass the processed image onto the next function! Instead of ending up with many nested callbacks, we get a clean &lt;code&gt;then&lt;/code&gt; chain. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fu9l3lxwxlxgv2edv79xh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fu9l3lxwxlxgv2edv79xh.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Perfect! This syntax already looks way better than the nested callbacks.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Microtasks and (Macro)tasks
&lt;/h2&gt;

&lt;p&gt;Okay so we know a little better how to create a promise and how to extract values out of a promise. Let's add some more code to the script, and run it again:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fey4ubnv5yjgi6hbh97xq.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fey4ubnv5yjgi6hbh97xq.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Wait what?! 🤯&lt;/p&gt;

&lt;p&gt;First, &lt;code&gt;Start!&lt;/code&gt; got logged. Okay we could've seen that one coming: &lt;code&gt;console.log('Start!')&lt;/code&gt; is on the very first line! However, the second value that got logged was &lt;code&gt;End!&lt;/code&gt;, and &lt;em&gt;not&lt;/em&gt; the value of the resolved promise! Only after &lt;code&gt;End!&lt;/code&gt; was logged, the value of the promise got logged. What's going on here?&lt;/p&gt;

&lt;p&gt;We've finally seen the true power of promises! 🚀 Although JavaScript is single-threaded, we can add asynchronous behavior using a &lt;code&gt;Promise&lt;/code&gt;!&lt;/p&gt;




&lt;p&gt;But wait, haven't we seen that before? 🤔 In the &lt;a href="https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif"&gt;JavaScript event loop&lt;/a&gt;, can't we also use methods native to the browser such as &lt;code&gt;setTimeout&lt;/code&gt; to create some sort of asynchronous behavior? &lt;/p&gt;

&lt;p&gt;Yes! However, within the Event Loop, there are actually two types of queues: the &lt;strong&gt;(macro)task queue&lt;/strong&gt; (or just called the &lt;strong&gt;task queue&lt;/strong&gt;), and the &lt;strong&gt;microtask queue&lt;/strong&gt;. The (macro)task queue is for &lt;strong&gt;(macro)tasks&lt;/strong&gt; and the microtask queue is for &lt;strong&gt;microtasks&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;So what's a &lt;em&gt;(macro)task&lt;/em&gt; and what's a &lt;em&gt;microtask&lt;/em&gt;? Although there are a few more than I'll cover here, the most common are shown in the table below!&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
    &lt;td&gt;
        (Macro)task
    &lt;/td&gt;
     &lt;td&gt;
         &lt;code&gt;setTimeout&lt;/code&gt; | &lt;code&gt;setInterval&lt;/code&gt; | &lt;code&gt;setImmediate&lt;/code&gt;
     &lt;/td&gt;
     &lt;/tr&gt;
     &lt;tr&gt;
     &lt;td&gt;
         Microtask
     &lt;/td&gt;
      &lt;td&gt;
          &lt;code&gt;process.nextTick&lt;/code&gt; | &lt;code&gt;Promise callback&lt;/code&gt; | &lt;code&gt;queueMicrotask&lt;/code&gt;
      &lt;/td&gt;
 &lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Ahh, we see &lt;code&gt;Promise&lt;/code&gt; in the microtask list! 😃 When a &lt;code&gt;Promise&lt;/code&gt; resolves and calls its &lt;code&gt;then()&lt;/code&gt;, &lt;code&gt;catch()&lt;/code&gt; or &lt;code&gt;finally()&lt;/code&gt;, method, the callback within the method gets added to the &lt;strong&gt;microtask queue&lt;/strong&gt;! This means that the callback within the &lt;code&gt;then()&lt;/code&gt;, &lt;code&gt;catch()&lt;/code&gt; or &lt;code&gt;finally()&lt;/code&gt; method isn't executed immediately, essentially adding some async behavior to our JavaScript code! &lt;/p&gt;

&lt;p&gt;So when &lt;em&gt;is&lt;/em&gt; a &lt;code&gt;then()&lt;/code&gt;, &lt;code&gt;catch()&lt;/code&gt; or &lt;code&gt;finally()&lt;/code&gt; callback executed? The event loop gives a different priority to the tasks:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;All functions in that are currently in the &lt;strong&gt;call stack&lt;/strong&gt; get executed. When they returned a value, they get popped off the stack.&lt;/li&gt;
&lt;li&gt;When the call stack is empty, &lt;em&gt;all&lt;/em&gt; queued up &lt;strong&gt;microtasks&lt;/strong&gt; are popped onto the callstack one by one, and get executed! (Microtasks themselves can also return new microtasks, effectively creating an infinite microtask loop 😬)&lt;/li&gt;
&lt;li&gt;If both the call stack and microtask queue are empty, the event loop checks if there are tasks left on the (macro)task queue. The tasks get popped onto the callstack, executed, and popped off! &lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Let's take a look at a quick example, simply using:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Task1&lt;/code&gt;: a function that's added to the call stack immediately, for example by invoking it instantly in our code.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Task2&lt;/code&gt;, &lt;code&gt;Task3&lt;/code&gt;, &lt;code&gt;Task4&lt;/code&gt;:  microtasks, for example a promise &lt;code&gt;then&lt;/code&gt; callback, or a task added with &lt;code&gt;queueMicrotask&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Task5&lt;/code&gt;, &lt;code&gt;Task6&lt;/code&gt;: a (macro)task, for example a &lt;code&gt;setTimeout&lt;/code&gt; or &lt;code&gt;setImmediate&lt;/code&gt; callback&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F42eatw03fcha0e1qcrf0.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F42eatw03fcha0e1qcrf0.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First, &lt;code&gt;Task1&lt;/code&gt; returned a value and got popped off the call stack. Then, the engine checked for tasks queued in the microtask queue. Once all the tasks were put on the call stack and eventually popped off, the engine checked for tasks on the (macro)task queue, which got popped onto the call stack, and popped off when they returned a value.&lt;/p&gt;

&lt;p&gt;Okay okay enough pink boxes. Let's use it with some real code!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fg61wwyi8wchk2hpzeq4u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fg61wwyi8wchk2hpzeq4u.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this code, we have the macro task &lt;code&gt;setTimeout&lt;/code&gt;, and the microtask promise &lt;code&gt;then()&lt;/code&gt; callback. Once the engine reaches the line of the &lt;code&gt;setTimeout&lt;/code&gt; function. Let's run this code step-by-step, and see what gets logged!&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;Quick FYI - in the following examples I'm showing methods like &lt;code&gt;console.log&lt;/code&gt;, &lt;code&gt;setTimeout&lt;/code&gt; and &lt;code&gt;Promise.resolve&lt;/code&gt; being added to the call stack. They're internal methods and actually don't appear in stack traces - so don't worry if you're using the debugger and you don't see them anywhere! It just makes explaining this concept easier without adding a bunch of boilerplate code 🙂&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;On the first line, the engine encounters the &lt;code&gt;console.log()&lt;/code&gt; method. It gets added to the call stack, after which it logs the value &lt;code&gt;Start!&lt;/code&gt; to the console. The method gets popped off the call stack, and the engine continues.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F6cbjuexvy6z9ltk0bi18.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F6cbjuexvy6z9ltk0bi18.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The engine encounters the &lt;code&gt;setTimeout&lt;/code&gt; method, which gets popped on to the call stack. The &lt;code&gt;setTimeout&lt;/code&gt; method is native to the browser: its callback function (&lt;code&gt;() =&amp;gt; console.log('In timeout')&lt;/code&gt;) will get added to the Web API, until the timer is done. Although we provided the value &lt;code&gt;0&lt;/code&gt; for the timer, the call back still gets pushed to the Web API first, after which it gets added to the &lt;strong&gt;(macro)task queue&lt;/strong&gt;: &lt;code&gt;setTimeout&lt;/code&gt; is a macro task!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyqoemb6f32lvovge8yrp.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyqoemb6f32lvovge8yrp.gif"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;The engine encounters the &lt;code&gt;Promise.resolve()&lt;/code&gt; method. The &lt;code&gt;Promise.resolve()&lt;/code&gt; method gets added to the call stack, after which is resolves with the value &lt;code&gt;Promise!&lt;/code&gt;. Its &lt;code&gt;then&lt;/code&gt; callback function gets added to the &lt;strong&gt;microtask queue&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F6wxjxduh62fqt531e2rc.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F6wxjxduh62fqt531e2rc.gif"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;The engine encounters the &lt;code&gt;console.log()&lt;/code&gt; method. It gets added to the call stack immediately, after which it logs the value &lt;code&gt;End!&lt;/code&gt; to the console, gets popped off the call stack, and the engine continues.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fa6jk0exl137yka3oq9k4.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fa6jk0exl137yka3oq9k4.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The engine sees the callstack is empty now. Since the call stack is empty, it's going to check whether there are queued tasks in the &lt;strong&gt;microtask queue&lt;/strong&gt;! And yes there are, the promise &lt;code&gt;then&lt;/code&gt; callback is waiting for its turn! It gets popped onto the call stack, after which it logs the resolved value of the promise: the string &lt;code&gt;Promise!&lt;/code&gt;in this case.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flczn4fca41is4vpicr6w.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flczn4fca41is4vpicr6w.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The engine sees the call stack is empty, so it's going to check the microtask queue once again to see if tasks are queued. Nope, the microtask queue is all empty.&lt;/p&gt;

&lt;p&gt;It's time to check the &lt;strong&gt;(macro)task queue&lt;/strong&gt;: the &lt;code&gt;setTimeout&lt;/code&gt; callback is still waiting there! The &lt;code&gt;setTimeout&lt;/code&gt; callback gets popped on to the callstack. The callback function returns the &lt;code&gt;console.log&lt;/code&gt; method, which logs the string &lt;code&gt;"In timeout!"&lt;/code&gt;. The &lt;code&gt;setTimeout&lt;/code&gt; callback get popped off the callstack.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fp54casaaz9oq0g8ztpi5.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fp54casaaz9oq0g8ztpi5.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, all done! 🥳 It seems like the output we saw earlier wasn't so unexpected after all.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt; Async/Await
&lt;/h2&gt;

&lt;p&gt;ES7 introduced a new way to add async behavior in JavaScript and make working with promises easier! With the introduction of the &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;await&lt;/code&gt; keywords, we can create &lt;strong&gt;async&lt;/strong&gt; functions which implicitly return a promise. But.. how can we do that? 😮&lt;/p&gt;

&lt;p&gt;Previously, we saw that we can explicitly create promises using the &lt;code&gt;Promise&lt;/code&gt; object, whether it was by typing &lt;code&gt;new Promise(() =&amp;gt; {})&lt;/code&gt;, &lt;code&gt;Promise.resolve&lt;/code&gt;, or &lt;code&gt;Promise.reject&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Instead of explicitly using the &lt;code&gt;Promise&lt;/code&gt; object, we can now create asynchronous functions that &lt;em&gt;implicitly&lt;/em&gt; return an object! This means that we no longer have to write any &lt;code&gt;Promise&lt;/code&gt; object ourselves.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F72lqrcvy9lc8ehbpitd0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F72lqrcvy9lc8ehbpitd0.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Although the fact that &lt;strong&gt;async&lt;/strong&gt; functions implicitly return promises is pretty great, the real power of &lt;code&gt;async&lt;/code&gt; functions can be seen when using the &lt;code&gt;await&lt;/code&gt; keyword! With the &lt;code&gt;await&lt;/code&gt; keyword, we can &lt;em&gt;suspend&lt;/em&gt; the asynchronous function while we wait for the &lt;code&gt;await&lt;/code&gt;ed value return a resolved promise. If we want to get the value of this resolved promise, like we previously did with the &lt;code&gt;then()&lt;/code&gt; callback, we can assign variables to the &lt;code&gt;await&lt;/code&gt;ed promise value!&lt;/p&gt;

&lt;p&gt;So, we can &lt;em&gt;suspend&lt;/em&gt; an async function? Okay great but.. what does that even mean? &lt;/p&gt;

&lt;p&gt;Let's see what happens when we run the following block of code:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fe5duygomitj9o455107a.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fe5duygomitj9o455107a.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hmm.. What's happening here?&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fd27d7xxiekczftjyic4b.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fd27d7xxiekczftjyic4b.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First, the engine encounters a &lt;code&gt;console.log&lt;/code&gt;. It gets popped onto the call stack, after which &lt;code&gt;Before function!&lt;/code&gt; gets logged.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F9wqej2269vmntfcuxs9t.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F9wqej2269vmntfcuxs9t.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, we invoke the async function &lt;code&gt;myFunc()&lt;/code&gt;, after which the function body of &lt;code&gt;myFunc&lt;/code&gt; runs. On the very first line within the function body, we call another &lt;code&gt;console.log&lt;/code&gt;, this time with the string &lt;code&gt;In function!&lt;/code&gt;. The &lt;code&gt;console.log&lt;/code&gt; gets added to the call stack, logs the value, and gets popped off.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flch6lutxnl88j0durpyh.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flch6lutxnl88j0durpyh.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The function body keeps on being executed, which gets us to the second line. Finally, we see an &lt;code&gt;await&lt;/code&gt; keyword! 🎉 &lt;/p&gt;

&lt;p&gt;The first thing that happens is that the value that gets awaited gets executed: the function &lt;code&gt;one&lt;/code&gt; in this case. It gets popped onto the call stack, and eventually returns a resolved promise. Once the promise has resolved and &lt;code&gt;one&lt;/code&gt; returned a value, the engine encounters the &lt;code&gt;await&lt;/code&gt; keyword. &lt;/p&gt;

&lt;p&gt;When encountering an &lt;code&gt;await&lt;/code&gt; keyword, the &lt;code&gt;async&lt;/code&gt; function gets &lt;em&gt;suspended&lt;/em&gt;. ✋🏼 The execution of the function body &lt;strong&gt;gets paused&lt;/strong&gt;, and the rest of the async function gets run in a &lt;em&gt;microtask&lt;/em&gt; instead of a regular task! &lt;/p&gt;




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fb6l3psgewvtrtmrr60tg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fb6l3psgewvtrtmrr60tg.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that the async function &lt;code&gt;myFunc&lt;/code&gt; is suspended as it encountered the &lt;code&gt;await&lt;/code&gt; keyword, the engine jumps out of the async function and continues executing the code in the execution context in which the async function got called: the &lt;strong&gt;global execution context&lt;/strong&gt; in this case! 🏃🏽‍♀️&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fhlhrtuspjyrstifubdhs.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fhlhrtuspjyrstifubdhs.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, there are no more tasks to run in the global execution context! The event loop checks to see if there are any microtasks queued up: and there are! The async &lt;code&gt;myFunc&lt;/code&gt; function is queued up after resolving the valued of &lt;code&gt;one&lt;/code&gt;. &lt;code&gt;myFunc&lt;/code&gt; gets popped back onto the call stack, and continues running where it previously left off.&lt;/p&gt;

&lt;p&gt;The variable &lt;code&gt;res&lt;/code&gt; finally gets its value, namely the value of the resolved promise that &lt;code&gt;one&lt;/code&gt; returned! We invoke &lt;code&gt;console.log&lt;/code&gt; with the value of &lt;code&gt;res&lt;/code&gt;: the string &lt;code&gt;One!&lt;/code&gt; in this case. &lt;code&gt;One!&lt;/code&gt; gets logged to the console and gets popped off the call stack! 😊&lt;/p&gt;

&lt;p&gt;Finally, all done! Did you notice how &lt;code&gt;async&lt;/code&gt; functions are different compared to a promise &lt;code&gt;then&lt;/code&gt;? The &lt;code&gt;await&lt;/code&gt; keyword &lt;em&gt;suspends&lt;/em&gt; the &lt;code&gt;async&lt;/code&gt; function, whereas the Promise body would've kept on being executed if we would've used &lt;code&gt;then&lt;/code&gt;!&lt;/p&gt;




&lt;p&gt;Hm that was quite a lot of information! 🤯 No worries at all if you still feel a bit overwhelmed when working with Promises, I personally feel that it just takes experience to notice patterns and feel confident when working with asynchronous JavaScript. &lt;/p&gt;

&lt;p&gt;However, I hope that the "unexpected" or "unpredictable" behavior that you might encounter when working with async JavaScript makes a bit more sense now! &lt;/p&gt;

&lt;p&gt;And as always, feel free to reach out to me! 😊&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
 &lt;td&gt;✨ &lt;a href="https://www.twitter.com/lydiahallie" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;👩🏽‍💻 &lt;a href="https://www.instagram.com/theavocoder" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💻 &lt;a href="https://www.github.com/lydiahallie" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💡 &lt;a href="https://www.linkedin.com/in/lydia-hallie" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;📷 &lt;a href="https://www.youtube.com/channel/UC4EWKIKdKiDtAscQ9BIXwUw" rel="noopener noreferrer"&gt;YouTube&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💌 &lt;a href="mailto:lydiahallie.dev@gmail.com%22"&gt;Email&lt;/a&gt;
&lt;/td&gt;

&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;If you want to know more about promises &lt;strong&gt;states&lt;/strong&gt; (and &lt;strong&gt;fates&lt;/strong&gt;!), this Github repo does an excellent job explaining the differences. &lt;/p&gt;
&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/domenic" rel="noopener noreferrer"&gt;
        domenic
      &lt;/a&gt; / &lt;a href="https://github.com/domenic/promises-unwrapping" rel="noopener noreferrer"&gt;
        promises-unwrapping
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      The ES6 promises spec, as per September 2013 TC39 meeting
    &lt;/h3&gt;
  &lt;/div&gt;
&lt;/div&gt;


</description>
      <category>javascript</category>
      <category>node</category>
      <category>webdev</category>
    </item>
    <item>
      <title>🌳🚀 CS Visualized: Useful Git Commands</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Wed, 01 Apr 2020 16:48:56 +0000</pubDate>
      <link>https://dev.to/lydiahallie/cs-visualized-useful-git-commands-37p1</link>
      <guid>https://dev.to/lydiahallie/cs-visualized-useful-git-commands-37p1</guid>
      <description>&lt;p&gt;Although Git is a very powerful tool, I think most people would agree when I say it can also be... a total nightmare 😐 I've always found it very useful to visualize in my head what's happening when working with Git: how are the branches interacting when I perform a certain command, and how will it affect the history? Why did my coworker cry when I did a hard reset on &lt;code&gt;master&lt;/code&gt;, &lt;code&gt;force push&lt;/code&gt;ed to origin and &lt;code&gt;rimraf&lt;/code&gt;'d the &lt;code&gt;.git&lt;/code&gt; folder?&lt;/p&gt;

&lt;p&gt;I thought it would be the perfect use case to create some visualized examples of the most common and useful commands! 🥳 Many of the commands I'm covering have optional arguments that you can use in order to change their behavior. In my examples, I'll cover the default behavior of the commands without adding (too many) config options! 😄 &lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
    &lt;tr&gt;
&lt;td&gt;
      Merge
&lt;/td&gt;
   
&lt;td&gt;
      Rebase
&lt;/td&gt;
   
&lt;td&gt;
      Reset
&lt;/td&gt;
   
&lt;td&gt;
      Revert
&lt;/td&gt;
  
&lt;td&gt;
      Cherry-Pick
&lt;/td&gt;
   
&lt;td&gt;
      Fetch
&lt;/td&gt;
  
&lt;td&gt;
      Pull
&lt;/td&gt;
   
&lt;td&gt;
      Reflog
&lt;/td&gt;
    &lt;/tr&gt;

&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Merging
&lt;/h2&gt;

&lt;p&gt;Having multiple branches is extremely convenient to keep new changes separated from each other, and to make sure you don't accidentally push unapproved or broken changes to production. Once the changes have been approved, we want to get these changes in our production branch!&lt;/p&gt;

&lt;p&gt;One way to get the changes from one branch to another is by performing a &lt;code&gt;git merge&lt;/code&gt;! There are two types of merges Git can perform: a &lt;strong&gt;fast-forward&lt;/strong&gt;, or a &lt;strong&gt;no-fast-forward&lt;/strong&gt; 🐢&lt;/p&gt;

&lt;p&gt;This may not make a lot of sense right now, so let's look at the differences!&lt;/p&gt;

&lt;h3&gt;
  
  
  Fast-forward (&lt;code&gt;--ff&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;fast-forward merge&lt;/strong&gt; can happen when the current branch has no extra commits compared to the branch we’re merging. Git is... &lt;em&gt;lazy&lt;/em&gt; and will first try to perform the easiest option: the fast-forward! This type of merge doesn’t create a new commit, but rather merges the commit(s) on the branch we’re merging right in the current branch 🥳&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F894znjv4oo9agqiz4dql.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F894znjv4oo9agqiz4dql.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Perfect! We now have all the changes that were made on the &lt;code&gt;dev&lt;/code&gt; branch available on the &lt;code&gt;master&lt;/code&gt; branch. So, what's the &lt;strong&gt;no-fast-forward&lt;/strong&gt; all about?&lt;/p&gt;

&lt;h3&gt;
  
  
  No-fast-foward (&lt;code&gt;--no-ff&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;It's great if your current branch doesn't have any extra commits compared to the branch that you want to merge, but unfortunately that's rarely the case! If we committed changes on the current branch that the branch we want to merge doesn't have, git will perform a &lt;em&gt;no-fast-forward&lt;/em&gt; merge. &lt;/p&gt;

&lt;p&gt;With a no-fast-forward merge, Git creates a new &lt;em&gt;merging commit&lt;/em&gt; on the active branch. The commit's parent commits point to both the active branch and the branch that we want to merge!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Frf1o2b6eduboqwkigg3w.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Frf1o2b6eduboqwkigg3w.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;No big deal, a perfect merge! 🎉 The &lt;code&gt;master&lt;/code&gt; branch now contains all the changes that we've made on the &lt;code&gt;dev&lt;/code&gt; branch. &lt;/p&gt;

&lt;h3&gt;
  
  
  Merge Conflicts
&lt;/h3&gt;

&lt;p&gt;Although Git is good at deciding how to merge branches and add changes to files, it cannot always make this decision all by itself 🙂 This can happen when the two branches we're trying to merge have changes on the same line in the same file, or if one branch deleted a file that another branch modified, and so on.&lt;/p&gt;

&lt;p&gt;In that case, Git will ask you to help decide which of the two options we want to keep! Let's say that on both branches, we edited the first line in the &lt;code&gt;README.md&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fm3nxmp67mqof5sa3iik9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fm3nxmp67mqof5sa3iik9.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If we want to merge &lt;code&gt;dev&lt;/code&gt; into &lt;code&gt;master&lt;/code&gt;, this will end up in a merge conflict: would you like the title to be &lt;code&gt;Hello!&lt;/code&gt; or &lt;code&gt;Hey!&lt;/code&gt;? &lt;/p&gt;

&lt;p&gt;When trying to merge the branches, Git will show you where the conflict happens. We can manually remove the changes we don't want to keep, save the changes, add the changed file again, and commit the changes 🥳&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbcd5ajtoc0g5dxzmpfbq.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbcd5ajtoc0g5dxzmpfbq.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yay! Although merge conflicts are often quite annoying, it makes total sense: Git shouldn't just &lt;em&gt;assume&lt;/em&gt; which change we want to keep. &lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Rebasing
&lt;/h2&gt;

&lt;p&gt;We just saw how we could apply changes from one branch to another by performing a &lt;code&gt;git merge&lt;/code&gt;. Another way of adding changes from one branch to another is by performing a &lt;code&gt;git rebase&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;git rebase&lt;/code&gt; &lt;em&gt;copies&lt;/em&gt; the commits from the current branch, and puts these copied commits on top of the specified branch. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdwyukhq8yj2xliq4i50e.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdwyukhq8yj2xliq4i50e.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Perfect, we now have all the changes that were made on the &lt;code&gt;master&lt;/code&gt; branch available on the &lt;code&gt;dev&lt;/code&gt; branch! 🎊&lt;/p&gt;

&lt;p&gt;A big difference compared to merging, is that Git won't try to find out which files to keep and not keep. The branch that we're rebasing always has the latest changes that we want to keep! You won't run into any merging conflicts this way, and keeps a nice linear Git history.&lt;/p&gt;

&lt;p&gt;This example shows rebasing on the &lt;code&gt;master&lt;/code&gt; branch. In bigger projects, however, you usually don't want to do that. A &lt;code&gt;git rebase&lt;/code&gt; &lt;strong&gt;changes the history of the project&lt;/strong&gt; as new hashes are created for the copied commits! &lt;/p&gt;

&lt;p&gt;Rebasing is great whenever you're working on a feature branch, and the master branch has been updated. You can get all the updates on your branch, which would prevent future merging conflicts! 😄&lt;/p&gt;

&lt;h3&gt;
  
  
  Interactive Rebase
&lt;/h3&gt;

&lt;p&gt;Before rebasing the commits, we can modify them! 😃 We can do so with an &lt;em&gt;interactive rebase&lt;/em&gt;. An interactive rebase can also be useful on the branch you're currently working on, and want to modify some commits.&lt;/p&gt;

&lt;p&gt;There are 6 actions we can perform on the commits we're rebasing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;reword&lt;/code&gt;: Change the commit message&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;edit&lt;/code&gt;: Amend this commit&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;squash&lt;/code&gt;: Meld commit into the previous commit&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;fixup&lt;/code&gt;: Meld commit into the previous commit, without keeping the commit's log message&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;exec&lt;/code&gt;: Run a command on each commit we want to rebase&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;drop&lt;/code&gt;: Remove the commit&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Awesome! This way, we can have full control over our commits. If we want to remove a commit, we can just &lt;code&gt;drop&lt;/code&gt; it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fmsofpv7k6rcmpaaefscm.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fmsofpv7k6rcmpaaefscm.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Or if we want to squash multiple commits together to get a cleaner history, no problem! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbc1r460xx1i0blu0lnnm.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbc1r460xx1i0blu0lnnm.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Interactive rebasing gives you a lot of control over the commits you're trying to rebase, even on the current active branch! &lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Resetting
&lt;/h2&gt;

&lt;p&gt;It can happen that we committed changes that we didn't want later on. Maybe it's a &lt;code&gt;WIP&lt;/code&gt; commit, or maybe a commit that introduced bugs! 🐛 In that case, we can perform a &lt;code&gt;git reset&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;git reset&lt;/code&gt; gets rid of all the current staged files and gives us control over where &lt;code&gt;HEAD&lt;/code&gt; should point to. &lt;/p&gt;

&lt;h3&gt;
  
  
  Soft reset
&lt;/h3&gt;

&lt;p&gt;A &lt;em&gt;soft reset&lt;/em&gt; moves &lt;code&gt;HEAD&lt;/code&gt; to the specified commit (or the index of the commit compared to &lt;code&gt;HEAD&lt;/code&gt;), without getting rid of the changes that were introduced on the commits afterward!  &lt;/p&gt;

&lt;p&gt;Let's say that we don't want to keep the commit &lt;code&gt;9e78i&lt;/code&gt; which added a &lt;code&gt;style.css&lt;/code&gt; file, and we also don't want to keep the commit &lt;code&gt;035cc&lt;/code&gt; which added an &lt;code&gt;index.js&lt;/code&gt; file. However, we do want to keep the newly added &lt;code&gt;style.css&lt;/code&gt; and &lt;code&gt;index.js&lt;/code&gt; file! A perfect use case for a soft reset.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fje5240aqa5uw9d8j3ibb.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fje5240aqa5uw9d8j3ibb.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;When typing &lt;code&gt;git status&lt;/code&gt;, you'll see that we still have access to all the changes that were made on the previous commits. This is great, as this means that we can fix the contents of these files and commit them again later on!&lt;/p&gt;

&lt;h3&gt;
  
  
  Hard reset
&lt;/h3&gt;

&lt;p&gt;Sometimes, we don't want to keep the changes that were introduced by certain commits. Unlike a soft reset, we shouldn't need to have access to them any more. Git should simply reset its state back to where it was on the specified commit: this even includes the changes in your working directory and staged files! 💣&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fhlh0kowt3hov1xhcku38.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fhlh0kowt3hov1xhcku38.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Git has discarded the changes that were introduced on &lt;code&gt;9e78i&lt;/code&gt; and &lt;code&gt;035cc&lt;/code&gt;, and reset its state to where it was on commit &lt;code&gt;ec5be&lt;/code&gt;. &lt;/p&gt;




&lt;h3&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Reverting
&lt;/h3&gt;

&lt;p&gt;Another way of undoing changes is by performing a &lt;code&gt;git revert&lt;/code&gt;. By reverting a certain commit, we create a &lt;em&gt;new commit&lt;/em&gt; that contains the reverted changes!&lt;/p&gt;

&lt;p&gt;Let's say that &lt;code&gt;ec5be&lt;/code&gt; added an &lt;code&gt;index.js&lt;/code&gt; file. Later on, we actually realize we didn't want this change introduced by this commit anymore! Let's revert the &lt;code&gt;ec5be&lt;/code&gt; commit. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F3kkd2ahn41zixs12xgpf.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F3kkd2ahn41zixs12xgpf.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Perfect! Commit &lt;code&gt;9e78i&lt;/code&gt; reverted the changes that were introduced by the &lt;code&gt;ec5be&lt;/code&gt; commit. Performing a &lt;code&gt;git revert&lt;/code&gt; is very useful in order to undo a certain commit, without modifying the history of the branch.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Cherry-picking
&lt;/h2&gt;

&lt;p&gt;When a certain branch contains a commit that introduced changes we need on our active branch, we can &lt;code&gt;cherry-pick&lt;/code&gt; that command! By &lt;code&gt;cherry-pick&lt;/code&gt;ing a commit, we create a new commit on our active branch that contains the changes that were introduced by the &lt;code&gt;cherry-pick&lt;/code&gt;ed commit.&lt;/p&gt;

&lt;p&gt;Say that commit &lt;code&gt;76d12&lt;/code&gt; on the &lt;code&gt;dev&lt;/code&gt; branch added a change to the &lt;code&gt;index.js&lt;/code&gt; file that we want in our &lt;code&gt;master&lt;/code&gt; branch. We don't want the &lt;em&gt;entire&lt;/em&gt; we just care about this one single commit! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F2dkjx4yeaal10xyvj29v.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F2dkjx4yeaal10xyvj29v.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cool, the master branch now contains the changes that &lt;code&gt;76d12&lt;/code&gt; introduced! &lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Fetching
&lt;/h2&gt;

&lt;p&gt;If we have a remote Git branch, for example a branch on Github, it can happen that the remote branch has commits that the current branch doesn't have! Maybe another branch got merged, your colleague pushed a quick fix, and so on.&lt;/p&gt;

&lt;p&gt;We can get these changes locally, by performing a &lt;code&gt;git fetch&lt;/code&gt; on the remote branch! It doesn't affect your local branch in any way: a &lt;code&gt;fetch&lt;/code&gt; simply downloads new data. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbulx1voegfji4vwgndh4.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbulx1voegfji4vwgndh4.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can now see all the changes that have been made since we last pushed! We can decide what we want to do with the new data now that we have it locally.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Pulling
&lt;/h2&gt;

&lt;p&gt;Although a &lt;code&gt;git fetch&lt;/code&gt; is very useful in order to get the remote information of a branch, we can also perform a &lt;code&gt;git pull&lt;/code&gt;. A &lt;code&gt;git pull&lt;/code&gt; is actually two commands in one: a &lt;code&gt;git fetch&lt;/code&gt;, and a &lt;code&gt;git merge&lt;/code&gt;. When we're pulling changes from the origin, we're first fetching all the data like we did with a &lt;code&gt;git fetch&lt;/code&gt;, after which the latest changes are automatically merged into the local branch. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fzifpnl1h6a4tk4qdc9sy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fzifpnl1h6a4tk4qdc9sy.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Awesome, we're now perfectly in sync with the remote branch and have all the latest changes! 🤩&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;Reflog
&lt;/h2&gt;

&lt;p&gt;Everyone makes mistakes, and that's totally okay! Sometimes it may feel like you've screwed up your git repo so badly that you just want to delete it entirely.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git reflog&lt;/code&gt; is a very useful command in order to show a log of all the actions that have been taken!  This includes merges, resets, reverts: basically any alteration to your branch.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F1aqek1py1knwl926ele7.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F1aqek1py1knwl926ele7.gif" alt="Alt Text"&gt;&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;If you made a mistake, you can easily redo this by resetting &lt;code&gt;HEAD&lt;/code&gt; based on the information that &lt;code&gt;reflog&lt;/code&gt; gives us! &lt;/p&gt;

&lt;p&gt;Say that we actually didn't want to merge the origin branch. When we execute the &lt;code&gt;git reflog&lt;/code&gt; command, we see that the state of the repo before the merge is at &lt;code&gt;HEAD@{1}&lt;/code&gt;. Let's perform a &lt;code&gt;git reset&lt;/code&gt; to point HEAD back to where it was on &lt;code&gt;HEAD@{1}&lt;/code&gt;!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F9z9rhtbw7mrigp0miijz.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F9z9rhtbw7mrigp0miijz.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can see that the latest action has been pushed to the &lt;code&gt;reflog&lt;/code&gt;!&lt;/p&gt;




&lt;p&gt;Git has so many useful porcelain and plumbing commands, I wish I could cover them all! 😄 I know there are many other commands or alterations that I didn't have time for to cover right now - let me know what your favorite/most useful commands are, and I may cover them in another post!&lt;/p&gt;

&lt;p&gt;And as always, feel free to reach out to me! 😊&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
 &lt;td&gt;✨ &lt;a href="https://www.twitter.com/lydiahallie" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;👩🏽‍💻 &lt;a href="https://www.instagram.com/theavocoder" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💻 &lt;a href="https://www.github.com/lydiahallie" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💡 &lt;a href="https://www.linkedin.com/in/lydia-hallie" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;📷 &lt;a href="https://www.youtube.com/channel/UC4EWKIKdKiDtAscQ9BIXwUw" rel="noopener noreferrer"&gt;YouTube&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💌 &lt;a href="mailto:lydiahallie.dev@gmail.com%22"&gt;Email&lt;/a&gt;
&lt;/td&gt;

&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

</description>
      <category>git</category>
      <category>computerscience</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>⭐️ Interactive JavaScript Quiz #2</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Mon, 09 Mar 2020 06:28:11 +0000</pubDate>
      <link>https://dev.to/lydiahallie/interactive-javascript-quiz-2-4pi1</link>
      <guid>https://dev.to/lydiahallie/interactive-javascript-quiz-2-4pi1</guid>
      <description>&lt;p&gt;This is the &lt;strong&gt;second&lt;/strong&gt; post of the JavaScript Quiz series! Make sure to check out the first one 🥳 Before starting this quiz, it may be useful to read through some of my older Dev.to posts! 😃&lt;/p&gt;

&lt;blockquote&gt;

&lt;div class="ltag__link"&gt;
  &lt;a href="/lydiahallie" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F198900%2Fd19268b1-6b0b-4530-9889-64fcf0a19d6d.png" alt="lydiahallie"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/lydiahallie/javascript-visualized-generators-and-iterators-e36" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;💡🎁 JavaScript Visualized: Generators and Iterators&lt;/h2&gt;
      &lt;h3&gt;Lydia Hallie ・ Jan 16 '20&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#javascript&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#node&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;
 &lt;div class="ltag__link"&gt;
  &lt;a href="/lydiahallie" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F198900%2Fd19268b1-6b0b-4530-9889-64fcf0a19d6d.png" alt="lydiahallie"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/lydiahallie/javascript-visualized-prototypal-inheritance-47co" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;🎉👨‍👩‍👧‍👧 JavaScript Visualized: Prototypal Inheritance&lt;/h2&gt;
      &lt;h3&gt;Lydia Hallie ・ Jan 3 '20&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#javascript&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#computerscience&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#webdev&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;
 &lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/lydiahallie" rel="noopener noreferrer"&gt;
        lydiahallie
      &lt;/a&gt; / &lt;a href="https://github.com/lydiahallie/javascript-questions" rel="noopener noreferrer"&gt;
        javascript-questions
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      A long list of (advanced) JavaScript questions, and their explanations ✨  
    &lt;/h3&gt;
  &lt;/div&gt;
&lt;/div&gt;
 Of course, the examples are still minimal and don't show "the best/most performant way to do it". Sometimes I have to do things a certain way in order to be able to show certain behavior that may happen, and explain it that way 🙂
&lt;/blockquote&gt;

&lt;p&gt;Okay, ready? Let's get started!&lt;/p&gt;




&lt;h4&gt;
  
  
  1. What's the output?
&lt;/h4&gt;

&lt;p&gt;&lt;iframe src="https://jsfiddle.net/lydiahallie/wt3cafde/4//embedded/result//dark" width="100%" height="600"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h5&gt;
  
  
  Explanation
&lt;/h5&gt;

&lt;p&gt;In this code snippet, we have a &lt;code&gt;person&lt;/code&gt; object and two arrow functions: &lt;code&gt;changeAge&lt;/code&gt; and &lt;code&gt;changeAgeAndName&lt;/code&gt;. The two arrow functions expect a parameter &lt;code&gt;x&lt;/code&gt;. If we don't provide a value  (or provide &lt;code&gt;undefined&lt;/code&gt;) for &lt;code&gt;x&lt;/code&gt; while invoking either &lt;code&gt;changeAge&lt;/code&gt; or &lt;code&gt;changeAgeAndName&lt;/code&gt;, the value of &lt;code&gt;x&lt;/code&gt; will be equal to &lt;code&gt;{...person}&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;First, we invoke the &lt;code&gt;changeAge&lt;/code&gt; function. We pass an object: the &lt;code&gt;person&lt;/code&gt; object! The default variable &lt;code&gt;{ ...person }&lt;/code&gt; won't be used: we provided a value after all 😊&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;changeAge&lt;/code&gt; function increments the value of the &lt;code&gt;age&lt;/code&gt; property on the object that &lt;code&gt;x&lt;/code&gt; holds a reference to, by &lt;code&gt;1&lt;/code&gt;. This means that the value of &lt;code&gt;age&lt;/code&gt; on the &lt;code&gt;person&lt;/code&gt; object will be incremented by one. &lt;br&gt;
The &lt;code&gt;person&lt;/code&gt; object is now &lt;code&gt;{ name: "Lydia", age: 22 }&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fj5hwu1hwa40wymvz6v95.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fj5hwu1hwa40wymvz6v95.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, we invoke the &lt;code&gt;changeAgeAndName&lt;/code&gt; function &lt;em&gt;without&lt;/em&gt; providing a value. This means that the value of &lt;code&gt;x&lt;/code&gt; will be equal to the default value &lt;code&gt;{ ...person }&lt;/code&gt;, which is a new object with the copied properties of the &lt;code&gt;person&lt;/code&gt; object: &lt;code&gt;{ name: "Lydia", age: 22 }&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fha5kudoh10qt0qhb5rev.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fha5kudoh10qt0qhb5rev.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;changeAgeAndName&lt;/code&gt; function increments the value of the &lt;code&gt;age&lt;/code&gt; property by &lt;code&gt;1&lt;/code&gt;, and sets the value of &lt;code&gt;name&lt;/code&gt; equal to &lt;code&gt;"Sarah"&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fkg3o6ijyg3mchloknz4c.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fkg3o6ijyg3mchloknz4c.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When we log the &lt;code&gt;person&lt;/code&gt; object, we'll only see the modification that was made by the &lt;code&gt;changeAge&lt;/code&gt; function: &lt;code&gt;{ name: "Lydia", age: 22 }&lt;/code&gt; 🎉&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ftj4a3ot10s6m2jvsu7ud.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ftj4a3ot10s6m2jvsu7ud.gif"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;h4&gt;
  
  
  2. What's the output?
&lt;/h4&gt;

&lt;p&gt;&lt;iframe src="https://jsfiddle.net/lydiahallie/ofpL19t3/2//embedded/result//dark" width="100%" height="600"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h5&gt;
  
  
  Explanation
&lt;/h5&gt;

&lt;p&gt;In this code snippet, we have a &lt;a href="https://dev.to/lydiahallie/javascript-visualized-generators-and-iterators-e36"&gt;generator function&lt;/a&gt; &lt;code&gt;range&lt;/code&gt;, which receives a &lt;code&gt;start&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt; value. It loops over the values that range between the value of &lt;code&gt;start&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt;, and yields a resolved promise for each value 🔥&lt;/p&gt;

&lt;p&gt;When we invoke the &lt;em&gt;immediately invoked function&lt;/em&gt;, we set the variable &lt;code&gt;gen&lt;/code&gt; equal to the iterator that got returned by the &lt;code&gt;range&lt;/code&gt; generator function.&lt;/p&gt;

&lt;p&gt;If we were to manually call the &lt;code&gt;next&lt;/code&gt; method on the &lt;code&gt;gen&lt;/code&gt; iterator, we'd see the &lt;em&gt;resolved promises&lt;/em&gt; for the values within the range that we provided.  We passed the values &lt;code&gt;1&lt;/code&gt; to &lt;code&gt;3&lt;/code&gt;, meaning that when we iterate over the iterator, it first yields &lt;code&gt;Promise {1}&lt;/code&gt;, then &lt;code&gt;Promise {2}&lt;/code&gt;, then &lt;code&gt;Promise {3}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwye586k7406drj1hi165.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwye586k7406drj1hi165.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can iterate over the yielded values of the iterator with a &lt;code&gt;for..in&lt;/code&gt; loop. This way, we don't have to manually call the &lt;code&gt;next()&lt;/code&gt; method each time 😃&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Faqw02ofjaukc8bxn5oj1.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Faqw02ofjaukc8bxn5oj1.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;We want to get the &lt;em&gt;resolved values&lt;/em&gt; of each promise. We can do so, by &lt;code&gt;awaiting&lt;/code&gt; each promise in a &lt;code&gt;for await .. in&lt;/code&gt; loop. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyiictvu6lgysysl32lax.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyiictvu6lgysysl32lax.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With the &lt;code&gt;for await...in&lt;/code&gt; loop, we can loop over the iterator and &lt;code&gt;await&lt;/code&gt; each value. By awaiting the resolved promises, the resolved values get returned: &lt;code&gt;1&lt;/code&gt;, &lt;code&gt;2&lt;/code&gt;, and &lt;code&gt;3&lt;/code&gt; in this case 💪🏼&lt;/p&gt;




&lt;h4&gt;
  
  
  3. What's the output?
&lt;/h4&gt;

&lt;p&gt;&lt;iframe src="https://jsfiddle.net/lydiahallie/4chdotqw/3//embedded/result//dark" width="100%" height="600"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h5&gt;
  
  
  Explanation
&lt;/h5&gt;

&lt;p&gt;We invoke the &lt;code&gt;getInfo&lt;/code&gt; function. On the very first line of this function, we're trying to log the value of the &lt;code&gt;randomValue&lt;/code&gt; variable.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F7pujts4gc7ngmgd5zv27.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F7pujts4gc7ngmgd5zv27.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;In this snippet, we see two variables called &lt;code&gt;randomValue&lt;/code&gt;, both declared with the &lt;code&gt;const&lt;/code&gt; keyword. Variables declared with the &lt;code&gt;const&lt;/code&gt; keyword are block-scoped, and not &lt;em&gt;initialized&lt;/em&gt; until we get to the line where we actually declare them. &lt;/p&gt;

&lt;p&gt;Within the &lt;code&gt;getInfo&lt;/code&gt; function, we try to access the block-scoped &lt;code&gt;randomValue&lt;/code&gt; before the line on which we declare the variable. The "zone" within a block scope that cannot reference the variable yet, is called the &lt;em&gt;temporal dead zone&lt;/em&gt;. When we try to reference an uninitialized variable, like we try to do by trying to log &lt;code&gt;typeof randomValue&lt;/code&gt;, a &lt;code&gt;ReferenceError&lt;/code&gt; gets thrown! ❌&lt;/p&gt;




&lt;p&gt;How'd it go? Did you get all 3 right? If yes, awesome! 🎉 If you made some mistakes, no worries at all! &lt;/p&gt;

&lt;p&gt;Hopefully you can learn something from the explanations, and take that new information into consideration the next time you may run into behavior that may seem "unexpected" 🙂&lt;/p&gt;

&lt;p&gt;Feel free to reach out to me!&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
 &lt;td&gt;✨ &lt;a href="https://www.twitter.com/lydiahallie" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;👩🏽‍💻 &lt;a href="https://www.instagram.com/theavocoder" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💻 &lt;a href="https://www.github.com/lydiahallie" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💡 &lt;a href="https://www.linkedin.com/in/lydia-hallie" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;📷 &lt;a href="https://www.youtube.com/channel/UC4EWKIKdKiDtAscQ9BIXwUw" rel="noopener noreferrer"&gt;YouTube&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💌 &lt;a href="mailto:lydiahallie.dev@gmail.com%22"&gt;Email&lt;/a&gt;
&lt;/td&gt;

&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

</description>
    </item>
    <item>
      <title>⭐️ Interactive JavaScript Quiz #1</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Tue, 25 Feb 2020 18:16:05 +0000</pubDate>
      <link>https://dev.to/lydiahallie/interactive-javascript-quiz-1-1flc</link>
      <guid>https://dev.to/lydiahallie/interactive-javascript-quiz-1-1flc</guid>
      <description>&lt;p&gt;We all know that JavaScript quizzes can be... awful and confusing 😐 The pointless &lt;code&gt;foo&lt;/code&gt; &lt;code&gt;bar&lt;/code&gt; &lt;code&gt;baz&lt;/code&gt; questions ruin all the fun of JavaScript and often just cause even more confusion!&lt;/p&gt;

&lt;p&gt;Last year, I made a GitHub Repo with tons of JavaScript questions that aren't questions like "tricky" or &lt;code&gt;"NaN === NaN"&lt;/code&gt;, but rather focus on more realistic situations. I thought it would be fun to make it into an interactive game series here on Dev.to, with animated explanations wherever possible! 🥳&lt;/p&gt;

&lt;blockquote&gt;

&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/lydiahallie" rel="noopener noreferrer"&gt;
        lydiahallie
      &lt;/a&gt; / &lt;a href="https://github.com/lydiahallie/javascript-questions" rel="noopener noreferrer"&gt;
        javascript-questions
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      A long list of (advanced) JavaScript questions, and their explanations ✨  
    &lt;/h3&gt;
  &lt;/div&gt;
&lt;/div&gt;
 Of course, the examples are still minimal and don't show "the best/most performant way to do it". Sometimes I have to do things a certain way in order to be able to show certain behavior that may happen, and explain it that way 🙂
&lt;/blockquote&gt;




&lt;h4&gt;
  
  
  1. What's the output?
&lt;/h4&gt;

&lt;p&gt;&lt;iframe src="https://jsfiddle.net/lydiahallie/d9x4zv6L/31//embedded/result//dark" width="100%" height="600"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h5&gt;
  
  
  Explanation
&lt;/h5&gt;

&lt;p&gt;With the &lt;code&gt;bind()&lt;/code&gt; and &lt;code&gt;call()&lt;/code&gt; method, we can decide to which object the &lt;code&gt;this&lt;/code&gt; keyword should refer. In this example, we're saying that the &lt;code&gt;this&lt;/code&gt; keyword within the &lt;code&gt;sayHi&lt;/code&gt; function should refer to the &lt;code&gt;person&lt;/code&gt; object by calling both &lt;code&gt;bind&lt;/code&gt; and &lt;code&gt;call&lt;/code&gt; on the &lt;code&gt;sayHi&lt;/code&gt; function 🥳&lt;/p&gt;

&lt;p&gt;Although the &lt;code&gt;bind()&lt;/code&gt; and &lt;code&gt;call()&lt;/code&gt; methods both allow us to specify which object the &lt;code&gt;this&lt;/code&gt; keyword should refer to, there's a tiny difference: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;bind()&lt;/code&gt; only returns a &lt;em&gt;&lt;strong&gt;copy of the bound function&lt;/strong&gt;&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;call()&lt;/code&gt; executes the bound function immediately&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;First, we log &lt;code&gt;sayHi.call(person, 21)&lt;/code&gt;. The &lt;code&gt;call&lt;/code&gt; method executes the (bound) function immediately, which results in &lt;code&gt;Lydia is 21&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Then, we log &lt;code&gt;sayHi.bind(person, 21)&lt;/code&gt;. The &lt;code&gt;bind&lt;/code&gt; method returns a &lt;em&gt;copy&lt;/em&gt; of the bound function, meaning that we're simply logging a new, copied function 😃&lt;/p&gt;




&lt;h4&gt;
  
  
  2. What's the output?
&lt;/h4&gt;

&lt;p&gt;&lt;iframe src="https://jsfiddle.net/lydiahallie/68o1s0uv/10//embedded/result//dark" width="100%" height="600"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h4&gt;
  
  
  Explanation
&lt;/h4&gt;

&lt;p&gt;Whenever we declare a set a variable equal to an object, we're not actually giving that variable the value of that object. Instead, we're giving it the value of a &lt;em&gt;reference&lt;/em&gt; (or actually &lt;strong&gt;pointer&lt;/strong&gt;) to that object in memory! ⚡️ &lt;/p&gt;

&lt;p&gt;In this case, we give the &lt;code&gt;person&lt;/code&gt; variable the value of a reference (pointer) to the object &lt;code&gt;{ name: "Lydia" }&lt;/code&gt; in memory.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdocd8s1q6w44symo5jv5.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdocd8s1q6w44symo5jv5.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, we declare a variable called &lt;code&gt;members&lt;/code&gt;. The value of &lt;code&gt;members&lt;/code&gt; is a reference to that array in memory! &lt;/p&gt;

&lt;p&gt;The first element in the array that &lt;code&gt;members&lt;/code&gt; has a reference to, is the object that &lt;code&gt;person&lt;/code&gt; has a reference to. When we set objects equal to each other, we're actually creating a &lt;em&gt;copy of the reference&lt;/em&gt;. This means that now &lt;code&gt;person&lt;/code&gt; and the first element in the &lt;code&gt;members&lt;/code&gt; array point to the same object in memory! 😃&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdrinnucl6rkpe7ywo54y.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdrinnucl6rkpe7ywo54y.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, we set &lt;code&gt;person&lt;/code&gt; equal to &lt;code&gt;null&lt;/code&gt;. This means that &lt;code&gt;person&lt;/code&gt; no longer has the value of the reference to the &lt;code&gt;{ name: "Lydia" }&lt;/code&gt; object in memory: it now has a reference to &lt;code&gt;null&lt;/code&gt;! 🎉 Since the first element in the array that &lt;code&gt;members&lt;/code&gt; has a reference to has its own, copied reference, the change of the value of &lt;code&gt;person&lt;/code&gt; does not affect the first element in that array! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fgq589tf2y8yb9uh74v4r.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fgq589tf2y8yb9uh74v4r.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since the first element in the &lt;code&gt;members&lt;/code&gt; array still has a reference to the object &lt;code&gt;{ name: "Lydia" }&lt;/code&gt;, that object gets returned when logging the first element!&lt;/p&gt;




&lt;h4&gt;
  
  
  3. What's the output?
&lt;/h4&gt;

&lt;p&gt;&lt;iframe src="https://jsfiddle.net/lydiahallie/5yezmo4c/1//embedded/result//dark" width="100%" height="600"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h4&gt;
  
  
  Explanation
&lt;/h4&gt;

&lt;p&gt;We have a list of groceries! One item in this list is our favorite item, and one item in this list is our least favorite item.&lt;/p&gt;

&lt;p&gt;First, we want to get the value of our favorite item, the grapes! One way of doing this, is by using the &lt;code&gt;find()&lt;/code&gt; method. The &lt;code&gt;find&lt;/code&gt; method returns the value of the item in the array that we're trying to find: the string with the grapes in this case &lt;code&gt;"🍇"&lt;/code&gt;. We assign the variable &lt;code&gt;favoriteItem&lt;/code&gt; to that returned value. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fe3zh399f04h4s9qho8em.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fe3zh399f04h4s9qho8em.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since the string &lt;code&gt;"🍇"&lt;/code&gt; is a primitive data type (it's a string! 🥳), the string gets passed by value. This means that the value of &lt;code&gt;favoriteItem&lt;/code&gt; is a copy of the item &lt;code&gt;"🍇"&lt;/code&gt; in the &lt;code&gt;groceries&lt;/code&gt; array, without containing any references to the &lt;code&gt;groceries&lt;/code&gt; array.&lt;/p&gt;

&lt;p&gt;We no longer want the grapes as our favorite item! Instead, we want to make the avocado &lt;code&gt;"🥑"&lt;/code&gt; our favorite item. The variable &lt;code&gt;favoriteItem&lt;/code&gt; gets reassigned with the value &lt;code&gt;"🥑"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fv2yfpee3lr689kqluupm.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fv2yfpee3lr689kqluupm.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, we want to find the index of our least favorite food: the string with the cheese &lt;code&gt;"🧀"&lt;/code&gt;! In order to find the index of the cheese, we can use the &lt;code&gt;indexOf&lt;/code&gt; method. To the &lt;code&gt;indexOf&lt;/code&gt; method, we pass the value of the element of which we're trying to get the index in the &lt;code&gt;groceries&lt;/code&gt; array: &lt;code&gt;"🧀"&lt;/code&gt; in this case.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdkch0iumrtob02vb3vd0.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdkch0iumrtob02vb3vd0.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Perfect! We now have the index of our least favorite item. Time to replace the least favorite item with some good food: a pizza &lt;code&gt;"🍕"&lt;/code&gt;. By replacing the value of the item on a specific index, we're modifying the &lt;code&gt;groceries&lt;/code&gt; array. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F5qsbxx232i3o9cjv0tch.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F5qsbxx232i3o9cjv0tch.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cool! We just changed the least favorite item in the groceries array. When logging the &lt;code&gt;groceries&lt;/code&gt; array, &lt;code&gt;["🍅", "🍇", "🍕"]&lt;/code&gt; got returned.&lt;/p&gt;




&lt;p&gt;How'd it go? Did you get all 3 right? If yes, awesome! 🎉 If you made some mistakes, no worries at all! &lt;/p&gt;

&lt;p&gt;Hopefully you can learn something from the explanations, and take that new information into consideration the next time you may run into behavior that may seem "unexpected" 🙂&lt;/p&gt;

&lt;p&gt;Feel free to reach out to me!&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
 &lt;td&gt;✨ &lt;a href="https://www.twitter.com/lydiahallie" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;👩🏽‍💻 &lt;a href="https://www.instagram.com/theavocoder" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💻 &lt;a href="https://www.github.com/lydiahallie" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💡 &lt;a href="https://www.linkedin.com/in/lydia-hallie" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;📷 &lt;a href="https://www.youtube.com/channel/UC4EWKIKdKiDtAscQ9BIXwUw" rel="noopener noreferrer"&gt;YouTube&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💌 &lt;a href="mailto:lydiahallie.dev@gmail.com%22"&gt;Email&lt;/a&gt;
&lt;/td&gt;

&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>💡🎁 JavaScript Visualized: Generators and Iterators</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Thu, 16 Jan 2020 05:22:29 +0000</pubDate>
      <link>https://dev.to/lydiahallie/javascript-visualized-generators-and-iterators-e36</link>
      <guid>https://dev.to/lydiahallie/javascript-visualized-generators-and-iterators-e36</guid>
      <description>&lt;p&gt;ES6 introduced something cool called &lt;strong&gt;generator functions&lt;/strong&gt; 🎉 Whenever I ask people about generator functions, the responses are basically: "I've seem them once, got confused, never looked at it again", "oh gosh no I've read so many blog posts about generator functions and I still don't get them", "I get them but why would anyone ever use that" 🤔 Or maybe that's just the conversations I've been having with myself because that's how I used to think for a long time! But they're actually quite cool.&lt;/p&gt;

&lt;p&gt;So, what are &lt;strong&gt;generator functions&lt;/strong&gt;? Let's first just look at a regular, old-fashioned function 👵🏼&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F2ta7m1vxju6j1dzg7t7c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F2ta7m1vxju6j1dzg7t7c.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yep absolutely nothing special about this! It's just a normal function that logs a value 4 times. Let's invoke it! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Funsiscmakhlgxl4dcji7.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Funsiscmakhlgxl4dcji7.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;"But Lydia why did you just waste 5 seconds of my life by making me look at this normal boring function", a very good question. Normal functions follow something called a &lt;strong&gt;run-to-completion&lt;/strong&gt; model: when we invoke a function, it will always run until it completes (well, unless there's an error somewhere). We can't just randomly &lt;em&gt;pause&lt;/em&gt; a function somewhere in the middle whenever we want to.&lt;/p&gt;

&lt;p&gt;Now here comes the cool part: generator functions  don't follow the &lt;strong&gt;run-to-completion&lt;/strong&gt; model! 🤯 Does this mean that we can randomly pause a generator function in the middle of executing it? Well, sort of! Let's take a look at what generator functions are and how we can use them.&lt;/p&gt;

&lt;p&gt;We create a generator function by writing an asterisk &lt;code&gt;*&lt;/code&gt; after the &lt;code&gt;function&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F7j9pxfpvmecip71ldjwg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F7j9pxfpvmecip71ldjwg.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But that's not all we have to do to use generator functions! Generator functions actually work in a completely different way compared to regular functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Invoking a generator function returns a &lt;strong&gt;generator object&lt;/strong&gt;, which is an iterator.&lt;/li&gt;
&lt;li&gt;We can use the &lt;code&gt;yield&lt;/code&gt; keyword in a generator function to "pause" the execution. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But what does that even mean!? &lt;/p&gt;

&lt;p&gt;Let's first go over the first one: &lt;em&gt;Invoking a generator function returns a &lt;strong&gt;generator object&lt;/strong&gt;&lt;/em&gt;. When we invoke a regular function, the function body gets executed and eventually returns a value. However when we invoke a generator function, a &lt;strong&gt;generator object&lt;/strong&gt; gets returned! Let's see what that looks like when we log the returned value. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Flyuivuuepy1hzpok8rc5.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Flyuivuuepy1hzpok8rc5.gif"&gt;&lt;/a&gt;&lt;br&gt;
Now, I can hear you screaming internally (or externally 🙃) because this can look a little overwhelming. But don't worry, we don't really have to use any of the properties you see logged here. So what's the generator object good for then? &lt;/p&gt;

&lt;p&gt;First we need to take a small step back, and answer the second difference between regular functions and generator functions: &lt;em&gt;We can use the &lt;code&gt;yield&lt;/code&gt; keyword in a generator function to "pause" the execution&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;With generator functions, we can write something like this (&lt;code&gt;genFunc&lt;/code&gt; is short for &lt;code&gt;generatorFunction&lt;/code&gt;):&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F1qo0upq0meh6gj2gs08o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F1qo0upq0meh6gj2gs08o.png"&gt;&lt;/a&gt; &lt;br&gt;
What's that &lt;code&gt;yield&lt;/code&gt; keyword doing there? The execution of the generator gets "paused" when it encounters a &lt;code&gt;yield&lt;/code&gt; keyword. And the best thing is that the next time we run the function, it remembered where it previously paused, and runs from there on! 😃 Basically what's happening here (don't worry this will be animated later on):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The first time it runs, it "pauses" on the first line and &lt;em&gt;yields&lt;/em&gt; the string value &lt;code&gt;'✨'&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;The second time it runs, it starts on the line of the previous &lt;code&gt;yield&lt;/code&gt; keyword. It then runs all the way down till the second &lt;code&gt;yield&lt;/code&gt; keyword and &lt;em&gt;yields&lt;/em&gt; the value &lt;code&gt;'💕'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The third time it runs, it start on the line of the previous yield keyword. It runs all the way down until it encounters the &lt;code&gt;return&lt;/code&gt; keyword, and &lt;em&gt;returns&lt;/em&gt; the value &lt;code&gt;'Done!'&lt;/code&gt;. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But... how can we invoke the function if we previously saw that invoking the generator function returned a generator object? 🤔 This is where the generator object comes into play! &lt;/p&gt;

&lt;p&gt;The generator object contains a &lt;code&gt;next&lt;/code&gt; method (on the prototype chain). This method is what we'll use to iterate the generator object. However, in order to remember the state of where it previously left off after yielding a value, we need to assign the generator object to a variable. I'll call it &lt;code&gt;genObj&lt;/code&gt; short for &lt;code&gt;generatorObject&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fy54clkzwbc9oemzgybh5.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fy54clkzwbc9oemzgybh5.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Yep, the same scary looking object as we saw before. Let's see what happens when we invoke the &lt;code&gt;next&lt;/code&gt; method on the &lt;code&gt;genObj&lt;/code&gt; generator object! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fryzc9gpzw4x5f0eqhzad.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fryzc9gpzw4x5f0eqhzad.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The generator ran until it encountered the first &lt;code&gt;yield&lt;/code&gt; keyword, which happened to be on the first line! It &lt;em&gt;yielded&lt;/em&gt; an object containing a &lt;code&gt;value&lt;/code&gt; property, and a &lt;code&gt;done&lt;/code&gt; property. &lt;/p&gt;

&lt;p&gt;```{&lt;br&gt;
&lt;br&gt;
 value: ... , done: ... }&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
The `value` property is equal to the value that we yielded.
The `done` property is a boolean value, which is only set to `true` once the generator function _*returned*_ a value (not yielded! 😊). 

We stopped iterating over the generator, which makes it look like the function just paused! How cool is that. Let's invoke the `next` method again! 😃

&amp;lt;img src="https://thepracticaldev.s3.amazonaws.com/i/e7hz87c6xtd31qjx19va.gif" /&amp;gt; 

First, we logged the string `First log!` to the console. This is neither a `yield` nor `return` keyword, so it continues! Then, it encountered a `yield` keyword with the value `'💕'`. An object gets _yielded_ with the `value` property of `'💕'` and a `done` property. The value of the `done` property is `false`, since we haven't _returned_ from the generator yet. 

We're almost there! Let's invoke `next` for the last time. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/33epxsx8znmhm0qojsuu.gif)

We logged the string `Second log!` to the console.  Then, it encountered a `return` keyword with the value `'Done!'`. An object gets returned with the `value` property of `'Done!'`. We actually _returned_ this time, so the value of `done` is set to `true`! 

The `done` property is actually very important. **We can only iterate a generator object _once_.** What?! So what happens when we call the `next` method again? 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/wooo83by4eh12akmg5wb.gif)

It simply returns `undefined` forever. In case you want to iterate it again, you just have to create a new generator object!

---

As we just saw, a generator function returns an iterator (the generator object). But.. wait an _iterator_? Does that mean we can use `for of` loops, and the spread operator on the returned object? Yas! 🤩

Let's try to spread the yielded values in an array, using the `[... ]` syntax.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/xgk99j592vbx3qirw5or.gif)

Or maybe by using a `for of` loop?!

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/98k242jz3bqorkjhukwl.gif)

Heck so many possibilities! 

But what makes an iterator an iterator? Because we can also use `for-of` loops and the spread syntax with arrays, strings, maps, and sets. It's actually because they implement the _iterator protocol_: the `[Symbol.iterator]`. Say that we have the following values (with very descriptive names lol 💁🏼‍♀️):
&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/hs2sf1oj537c56yaej1h.png" /&amp;gt;

The `array`, `string`, and `generatorObject` are all iterators! Let's take a look at the value of their `[Symbol.iterator]` property.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/a7inxsrvrp8ykg3xw6zu.gif)

But then what's the value of the `[Symbol.iterator]` on the values that aren't iterable? 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/tpuzuy58g8m7grxvqw8x.gif)

Yeah, it's just not there. So.. Can we simply just add the `[Symbol.iterator]` property manually, and make non-iterables iterable? Yes, we can! 😃

`[Symbol.iterator]` has to return an iterator, containing a `next` method which returns an object just like we saw before: `{ value: '...', done: false/true }`. 

To keep it simple (as lazy me likes to do) we can simply set the value of `[Symbol.iterator]` equal to a generator function, as this returns an iterator by default. Let's make the object an iterable, and the yielded value the entire object:
&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/oysyy7v71o2q9q9mrcsx.png" /&amp;gt;

See what happens when we use the spread syntax or a for-of loop on our `object` object now!

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/pw2qq1tkfbp8zccuecac.gif)

Or maybe we only wanted to get the object keys. "Oh well that's easy, we just yield `Object.keys(this)` instead of `this`"! 
&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/ankit4dn67unnwzfkv9y.png" /&amp;gt;

Hmm let's try that.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/75kf40lqcqrudzqgkeb7.gif)

Oh shoot. `Object.keys(this)` is an array, so the value that got yielded is an array. Then we spread this yielded array into another array, resulting in a nested array. We didn't want this, we just wanted to yield each individual key! 

Good news! 🥳 We can yield individual values from iterators within a generator using the `yield*` keyword, so the `yield` with an asterisk! Say that we have a generator function that first yield an avocado, then we want to yield the values of another iterator (an array in this case) individually. We can do so with the `yield*` keyword. We then _delegate_ to another generator! 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/jtyn5s5o3vdhjkbwwyb0.gif)

Each value of the delegated generator gets yielded, before it continued iterating the `genObj` iterator. 

This is exactly what we need to do in order to get all object keys individually! 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/btr4ytbb04c44qfs96v2.gif)

---

Another use of generator functions, is that we can (sort of) use them as observer functions. A generator can wait for incoming data, and only if that data is passed, it will process it. An example:
&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/fts36exs5chxacikjeo3.png" /&amp;gt;

A big difference here is that we don't just have `yield [value]` like we saw in the previous examples. Instead, we assign a value called `second`, and yield value the string `First!`. This is the value that will get yielded the first time we call the `next` method.

Let's see what happens when we call the `next` method for the first time on the iterable. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ob5a4yi79it9q2ben137.gif)

It encountered the `yield` on the first line, and yielded the value `First!`. So, what's the value of the variable `second`? 

That's actually the value that we pass to the `next` method the _next time we call it_! This time, let's pass the string `'I like JavaScript'`.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/l1840pp2k9h9bgpt1geo.gif)

It's important to see here that the first invocation of the `next` method doesn't keep track of any input yet. We simply start the observer by invoking it the first time. The generator waits for our input, before it continues, and possibly processes the value that we pass to the `next` method. 

 ---

So why would you ever want to use generator functions? 

One of the biggest advantages of generators is the fact that they are **lazily evaluated**. This means that the value that gets returned after invoking the `next` method, is only computed after we specifically asked for it! Normal functions don't have this: all the values are generated for you in case you need to use it some time in the future. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/7b24mkp7io3gmnn8pzwa.gif)

There are several other use cases, but I usually like to do it to have way more control when I'm iterating large datasets! 

Imagine we have a list of book clubs! 📚 To keep this example short and not one huge block of code, each book club just has one member. A member is currently reading several books, which is represented in the `books` array!

&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/8opapd1iddlgj1ljixje.png" /&amp;gt;

Now, we're looking for a book with the id `ey812`. In order to find that, we could potentially just use a nested for-loop or a `forEach` helper, but that means that we'd still be iterating through the data even after finding the team member we were looking for!

The awesome thing about generators, is that it doesn't keep on running unless we tell it to. This means that we can evaluate each returned item, and if it's the item we're looking for, we simply don't call `next`! Let's see what that would look like.

First, let's create a generator that iterates through the `books` array of each team member. We'll pass the team member's `book` array to the function, iterate through the array, and yield each book!

&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/vokf28crwuvbmksd57m5.png" /&amp;gt;

Perfect! Now we have to make a generator that iterates through the `clubMembers` array. We don't really care about the club member itself, we just need to iterate through their books. In the `iterateMembers` generator, let's delegate the `iterateBooks` iterator in order to just yield their books!

&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/fy8mxxjj0uvs6rarm6mi.png" /&amp;gt;

Almost there! The last step is to iterate through the bookclubs. Just like in the previous example, we don't really care about the bookclubs themselves, we just care about the club members (and especially their books). Let's delegate the `iterateClubMembers` iterator and pass the `clubMembers` array to it.

&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/x1lor0omqw9t5k2kq4iv.png" /&amp;gt;

In order to iterate through all this, we need to get the generator object iterable by passing the `bookClub` array to the `iterateBookClubs` generator. I'll just call the generator object `it` for now, for iterator.

&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/omg23omwi8a1d7nn1it3.png" /&amp;gt;

Let's invoke the `next` method, until we get a book with the id `ey812`.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/72ghm4ev6el3no9esk1l.gif)

Nice! We didn't have to iterate through all the data in order to get the book we were looking for. Instead, we just looked for the data on demand! of course, calling the `next` method manually each time isn't very efficient... So let's make a function instead! 

Let's pass an `id` to the function, which is the id of the book we're looking for. If the `value.id` is the id we're looking for, then simply return the entire `value` (the book object). Else, if it's not the correct `id`, invoke `next` again!  
&amp;lt;img width="500" src="https://thepracticaldev.s3.amazonaws.com/i/hxyeemfr3q8pqqotk51j.png" /&amp;gt;

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/x1zh0ygt5yfq5vb2f5at.gif)

Of course this was a tiny tiny data set. But just imagine that we have tons and tons of data, or maybe an incoming stream that we need to parse in order to just find one value. Normally, we'd have to wait for the entire dataset to be ready, in order to begin parsing. With generator functions, we can simply require small chunks of data, check that data, and the values are only generated when we invoke the `next` method! 

---

Don't worry if you're still all "what the heck is happening" mindset, generator functions are quite confusing until you've used them yourself and had some solid use cases for it! I hoped some terms are a bit clearer now, and as always: if you have any questions, feel free to reach out! 😃

&amp;lt;table&amp;gt;
  &amp;lt;tr&amp;gt;
 &amp;lt;td&amp;gt;✨ &amp;lt;a href="https://www.twitter.com/lydiahallie"&amp;gt;Twitter&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;👩🏽‍💻 &amp;lt;a href="https://www.instagram.com/theavocoder"&amp;gt;Instagram&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;💻 &amp;lt;a href="https://www.github.com/lydiahallie"&amp;gt;GitHub&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;💡 &amp;lt;a href="https://www.linkedin.com/in/lydia-hallie"&amp;gt;LinkedIn&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;📷 &amp;lt;a href="https://www.youtube.com/channel/UC4EWKIKdKiDtAscQ9BIXwUw"&amp;gt;YouTube&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;💌 &amp;lt;a href=mailto:lydiahallie.dev@gmail.com"&amp;gt;Email&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;

&amp;lt;/tr&amp;gt;
&amp;lt;/table&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>javascript</category>
      <category>node</category>
    </item>
    <item>
      <title>🎉👨‍👩‍👧‍👧 JavaScript Visualized: Prototypal Inheritance</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Fri, 03 Jan 2020 08:26:18 +0000</pubDate>
      <link>https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co</link>
      <guid>https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co</guid>
      <description>&lt;p&gt;Ever wondered why we can use built-in methods such as &lt;code&gt;.length&lt;/code&gt;, &lt;code&gt;.split()&lt;/code&gt;, &lt;code&gt;.join()&lt;/code&gt; on our strings, arrays, or objects? We never explicitly specified them, where do they come from? Now don't say "It's JavaScript lol no one knows, it's magic 🧚🏻‍♂️", it's actually because of something called &lt;em&gt;prototypal inheritance&lt;/em&gt;. It's pretty awesome, and you use it more often than you realize! &lt;/p&gt;

&lt;p&gt;We often have to create many objects of the same type. Say we have a website where people can browse dogs!&lt;/p&gt;

&lt;p&gt;For every dog, we need  object that represents that dog! 🐕 Instead of writing a new object each time, I'll use a constructor function (I know what you're thinking, I'll cover ES6 classes later on!) from which we can create Dog &lt;strong&gt;instances&lt;/strong&gt; using the &lt;code&gt;new&lt;/code&gt; keyword (this post isn't really about explaining constructor functions though, so I won't talk too much about that).&lt;/p&gt;

&lt;p&gt;Every dog has a name, a breed, a color, and a function to bark! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fcaurw7uuk62htpldgtln.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fcaurw7uuk62htpldgtln.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When we created the &lt;code&gt;Dog&lt;/code&gt; constructor function, it wasn't the only object we created. Automatically, we also created another object, called the &lt;em&gt;prototype&lt;/em&gt;! By default, this object contains a &lt;em&gt;constructor&lt;/em&gt; property, which is simply a reference to the original constructor function, &lt;code&gt;Dog&lt;/code&gt; in this case.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F9howj4i3zvlgun3svppp.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F9howj4i3zvlgun3svppp.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;prototype&lt;/code&gt; property on the Dog constructor function is non-enumerable, meaning that it doesn't show up when we try to access the objects properties. But it's still there! &lt;/p&gt;

&lt;p&gt;Okay so.. Why do we have this &lt;em&gt;property&lt;/em&gt; object? First, let's create some dogs that we want to show. To keep it simple, I'll call them &lt;code&gt;dog1&lt;/code&gt; and &lt;code&gt;dog2&lt;/code&gt;. &lt;code&gt;dog1&lt;/code&gt; is Daisy, a cute black Labrador! &lt;code&gt;dog2&lt;/code&gt; is Jack,  the fearless white Jack Russell 😎&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Flyajz4lade30ci2koirq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Flyajz4lade30ci2koirq.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's log &lt;code&gt;dog1&lt;/code&gt; to the console, and expand its properties!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ftt4yfoz8ckmxfofv3f9v.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ftt4yfoz8ckmxfofv3f9v.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We see the properties we added, like &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;breed&lt;/code&gt;, &lt;code&gt;color&lt;/code&gt;, and &lt;code&gt;bark&lt;/code&gt;.. but woah what is that &lt;code&gt;__proto__&lt;/code&gt; property! It's non-enumerable, meaning that it usually doesn't show up when we try to get the properties on the object. Let's expand it! 😃&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fdye57pcku5cfaz0er60c.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fdye57pcku5cfaz0er60c.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Woah it looks exactly like the &lt;code&gt;Dog.prototype&lt;/code&gt; object! Well guess what, &lt;code&gt;__proto__&lt;/code&gt; is a reference to the &lt;code&gt;Dog.prototype&lt;/code&gt; object. This is what &lt;strong&gt;prototypal inheritance&lt;/strong&gt; is all about: each instance of the constructor has access to the prototype of the constructor! 🤯&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ft6kiav029gl2e0hv1xct.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ft6kiav029gl2e0hv1xct.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;So why is this cool? Sometimes we have properties that all instances share. For example the &lt;code&gt;bark&lt;/code&gt; function in this case: it's the exact same for every instance, why create a new function each time we create a new dog, consuming memory each time? Instead, we can add it to the &lt;code&gt;Dog.prototype&lt;/code&gt; object! 🥳&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F59nlnyqioosaowj09xn8.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F59nlnyqioosaowj09xn8.gif"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Whenever we try to access a property on the instance, the engine first searches locally to see if the property is defined on the object itself. However, if it can't find the property we're trying to access, the engine &lt;strong&gt;walks down the prototype chain&lt;/strong&gt; through the &lt;code&gt;__proto__&lt;/code&gt; property! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ffabyyjot1s78mttyzzk8.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ffabyyjot1s78mttyzzk8.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now this is just one step, but it can contain several steps! If you followed along, you may have noticed that I didn't include one property when I expanded the &lt;code&gt;__proto__&lt;/code&gt; object showing &lt;code&gt;Dog.prototype&lt;/code&gt;. &lt;code&gt;Dog.prototype&lt;/code&gt; itself is an object, meaning that it's actually an instance of the &lt;code&gt;Object&lt;/code&gt; constructor! That means that &lt;code&gt;Dog.prototype&lt;/code&gt; also contains a &lt;code&gt;__proto__&lt;/code&gt; property, which is a reference to &lt;code&gt;Object.prototype&lt;/code&gt;! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F8vk5w6loliot818f2lcd.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F8vk5w6loliot818f2lcd.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, we have an answer to where all the built-in methods come from: they're on the prototype chain! 😃&lt;/p&gt;

&lt;p&gt;For example the &lt;code&gt;.toString()&lt;/code&gt; method. Is it defined locally on the &lt;code&gt;dog1&lt;/code&gt; object? Hmm no.. Is it defined on the object &lt;code&gt;dog1.__proto__&lt;/code&gt; has a reference to, namely &lt;code&gt;Dog.prototype&lt;/code&gt;? Also no! Is it defined on the object &lt;code&gt;Dog.prototype.__proto__&lt;/code&gt; has a reference to, namely &lt;code&gt;Object.prototype&lt;/code&gt;? Yes! 🙌🏼&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ffpt5nndkbq5kau0nqeqj.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ffpt5nndkbq5kau0nqeqj.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, we've just been using constructor functions (&lt;code&gt;function Dog() { ... }&lt;/code&gt;), which is still valid JavaScript. However, ES6 actually introduced an easier syntax for constructor functions and working with prototypes: classes!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Classes are only &lt;strong&gt;syntactical sugar&lt;/strong&gt; for constructor functions. Everything still works the same way!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We write classes with the &lt;code&gt;class&lt;/code&gt; keyword. A class has a &lt;code&gt;constructor&lt;/code&gt; function, which is basically the constructor function we wrote in the ES5 syntax! The properties that we want to add to the prototype, are defined on the classes body itself.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fqnbqubcipqjl5pb3i8ds.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fqnbqubcipqjl5pb3i8ds.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another great thing about classes, is that we can easily &lt;strong&gt;extend&lt;/strong&gt; other classes. &lt;/p&gt;

&lt;p&gt;Say that we want to show several dogs of the same breed, namely Chihuahuas! A chihuahua is (somehow... 😐) still a dog. To keep this example simple, I'll only pass the &lt;code&gt;name&lt;/code&gt; property to the Dog class for now instead of &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;breed&lt;/code&gt; and &lt;code&gt;color&lt;/code&gt;.  But these chihuahuas can also do something special, they have a small bark. Instead of saying &lt;code&gt;Woof!&lt;/code&gt;, a chihuahua can also say &lt;code&gt;Small woof!&lt;/code&gt; 🐕&lt;/p&gt;

&lt;p&gt;In an extended class, we can access the parent class' constructor using the &lt;code&gt;super&lt;/code&gt; keyword. The arguments the parent class' constructor expects, we have to pass to &lt;code&gt;super&lt;/code&gt;: &lt;code&gt;name&lt;/code&gt; in this case.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ftx25dar3duqo0z2bpfam.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ftx25dar3duqo0z2bpfam.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;myPet&lt;/code&gt; has access to both the &lt;code&gt;Chihuahua.prototype&lt;/code&gt; and &lt;code&gt;Dog.prototype&lt;/code&gt; (and automatically &lt;code&gt;Object.prototype&lt;/code&gt;, since &lt;code&gt;Dog.prototype&lt;/code&gt; is an object).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fqija16dju8t5j1ksy0ps.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fqija16dju8t5j1ksy0ps.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;Chihuahua.prototype&lt;/code&gt; has the &lt;code&gt;smallBark&lt;/code&gt; function, and &lt;code&gt;Dog.prototype&lt;/code&gt; has the &lt;code&gt;bark&lt;/code&gt; function, we can access both &lt;code&gt;smallBark&lt;/code&gt; and &lt;code&gt;bark&lt;/code&gt; on &lt;code&gt;myPet&lt;/code&gt;! &lt;/p&gt;

&lt;p&gt;Now as you can imagine, the prototype chain doesn't go on forever. Eventually there's an object which prototype is equal to &lt;code&gt;null&lt;/code&gt;: the &lt;code&gt;Object.prototype&lt;/code&gt; object in this case! If we try to access a property that's nowhere to be found locally or on the prototype chain, &lt;code&gt;undefined&lt;/code&gt; gets returned. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F1905zxijp45soy0jzle2.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F1905zxijp45soy0jzle2.gif"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Although I explained everything with constructor functions and classes here, another way to add prototypes to objects is with the &lt;code&gt;Object.create&lt;/code&gt; method. With this method, we create a new object, and can specify exactly what the prototype of that object should be! 💪🏼&lt;/p&gt;

&lt;p&gt;We do this, by passing an &lt;em&gt;existing object&lt;/em&gt; as argument to the &lt;code&gt;Object.create&lt;/code&gt; method. That object is the prototype of the object we create! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fkbwwsn1fd4gngd05tm9a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fkbwwsn1fd4gngd05tm9a.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's log the &lt;code&gt;me&lt;/code&gt; object we just created.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F6zzt8zpy85gtitxmpwi9.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F6zzt8zpy85gtitxmpwi9.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We didn't add any properties to the &lt;code&gt;me&lt;/code&gt; object, it simply only contains the non-enumerable &lt;code&gt;__proto__&lt;/code&gt; property! The &lt;code&gt;__proto__&lt;/code&gt; property holds a reference to the object we defined as the prototype: the &lt;code&gt;person&lt;/code&gt; object, which has a &lt;code&gt;name&lt;/code&gt; and an &lt;code&gt;age&lt;/code&gt; property. Since the &lt;code&gt;person&lt;/code&gt; object is an object, the value of the &lt;code&gt;__proto__&lt;/code&gt; property on the &lt;code&gt;person&lt;/code&gt; object is &lt;code&gt;Object.prototype&lt;/code&gt; (but to make it a bit easier to read,  I didn't expand that property in the gif!)&lt;/p&gt;




&lt;p&gt;Hopefully, you now understand why prototypal inheritance is such an important feature in the wonderful world of JavaScript! If you have questions, feel free to reach out to me! 😊&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
  &lt;tr&gt;
 &lt;td&gt;✨ &lt;a href="https://www.twitter.com/lydiahallie" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;👩🏽‍💻 &lt;a href="https://www.instagram.com/theavocoder" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💻 &lt;a href="https://www.github.com/lydiahallie" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💡 &lt;a href="https://www.linkedin.com/in/lydia-hallie" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;📷 &lt;a href="https://www.youtube.com/channel/UC4EWKIKdKiDtAscQ9BIXwUw" rel="noopener noreferrer"&gt;YouTube&lt;/a&gt;
&lt;/td&gt;
&lt;td&gt;💌 &lt;a href="mailto:lydiahallie.dev@gmail.com%22"&gt;Email&lt;/a&gt;
&lt;/td&gt;

&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;

</description>
      <category>javascript</category>
      <category>computerscience</category>
      <category>webdev</category>
    </item>
    <item>
      <title>🚀⚙️ JavaScript Visualized: the JavaScript Engine</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Fri, 13 Dec 2019 07:47:14 +0000</pubDate>
      <link>https://dev.to/lydiahallie/javascript-visualized-the-javascript-engine-4cdf</link>
      <guid>https://dev.to/lydiahallie/javascript-visualized-the-javascript-engine-4cdf</guid>
      <description>&lt;p&gt;JavaScript is cool (don't @ me), but how can a machine actually understand the code you've written? As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know &lt;em&gt;the basics&lt;/em&gt; of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳&lt;/p&gt;

&lt;p&gt;| &lt;strong&gt;Note:&lt;/strong&gt; This post is mainly based on the V8 engine used by Node.js and Chromium-based browsers. &lt;/p&gt;




&lt;p&gt;The HTML parser encounters a &lt;code&gt;script&lt;/code&gt; tag with a source. Code from this source gets loaded from either the &lt;strong&gt;network&lt;/strong&gt;, &lt;strong&gt;cache&lt;/strong&gt;, or an installed &lt;strong&gt;service worker&lt;/strong&gt;. The response is the requested script as a &lt;strong&gt;stream of bytes&lt;/strong&gt;, which the byte stream decoder takes care of! The &lt;strong&gt;byte stream decoder&lt;/strong&gt; decodes the stream of bytes as it’s being downloaded.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffb551fh9m1wdn8whtlyz.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffb551fh9m1wdn8whtlyz.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;The byte stream decoder creates &lt;strong&gt;tokens&lt;/strong&gt; from the decoded stream of bytes. For example, &lt;code&gt;0066&lt;/code&gt; decodes to &lt;code&gt;f&lt;/code&gt;,  &lt;code&gt;0075&lt;/code&gt; to &lt;code&gt;u&lt;/code&gt;,  &lt;code&gt;006e&lt;/code&gt; to &lt;code&gt;n&lt;/code&gt;, &lt;code&gt;0063&lt;/code&gt; to &lt;code&gt;c&lt;/code&gt;,  &lt;code&gt;0074&lt;/code&gt; to &lt;code&gt;t&lt;/code&gt;, &lt;code&gt;0069&lt;/code&gt; to &lt;code&gt;i&lt;/code&gt;,  &lt;code&gt;006f&lt;/code&gt; to &lt;code&gt;o&lt;/code&gt;, and  &lt;code&gt;006e&lt;/code&gt; to &lt;code&gt;n&lt;/code&gt; followed by a white space. Seems like you wrote &lt;code&gt;function&lt;/code&gt;! This is a reserved keyword in JavaScript, a token gets created, and sent to the parser (and &lt;em&gt;pre-parser&lt;/em&gt;, which I didn't cover in the gifs but will explain later). The same happens for the rest of the byte stream.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fbic727jhzu0i8uep8v0k.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fbic727jhzu0i8uep8v0k.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;The engine uses two parsers: the &lt;strong&gt;pre-parser&lt;/strong&gt;, and the &lt;strong&gt;parser&lt;/strong&gt;. In order to reduce the time it takes to load up a website, the engine tries to avoid parsing code that's not necessary right away. The preparser handles code that may be used later on, while the parser handles the code that’s needed immediately! If a certain function will only get invoked after a user clicks a button, it's not necessary that this code is compiled immediately just to load up a website. If the user eventually ends up clicking the button and requiring that piece of code, it gets sent to the parser.&lt;/p&gt;

&lt;p&gt;The parser creates nodes based on the tokens it receives from the byte stream decoder. With these nodes, it creates an Abstract Syntax Tree, or AST. 🌳&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fsgr7ih6t7zm2ek28rtg6.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fsgr7ih6t7zm2ek28rtg6.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Next, it's time for the &lt;strong&gt;interpreter&lt;/strong&gt;! The interpreter which walks through the AST, and generates &lt;strong&gt;byte code&lt;/strong&gt; based on the information that the AST contains. Once the byte code has been generated fully, the AST is deleted, clearing up memory space. Finally, we have something that a machine can work with! 🎉 &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fi5f0vmcjnkhireehicyn.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fi5f0vmcjnkhireehicyn.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Although byte code is fast, it can be faster. As this bytecode runs, information is being generated. It can detect whether certain behavior happens often, and the types of the data that’s been used. Maybe you've been invoking a function dozens of times: it's time to optimize this so it'll run even faster! 🏃🏽‍♀️&lt;/p&gt;

&lt;p&gt;The byte code, together with the generated type feedback, is sent to an &lt;strong&gt;optimizing compiler&lt;/strong&gt;. The optimizing compiler takes the byte code and type feedback, and generates highly optimized machine code from these. 🚀&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fongt4qftovd82sp2vihk.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fongt4qftovd82sp2vihk.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;JavaScript is a dynamically typed language, meaning that the types of data can change constantly. It would be extremely slow if the JavaScript engine had to check each time which data type a certain value has. &lt;/p&gt;

&lt;p&gt;In order to reduce the time it takes to interpret the code, optimized machine code only handles the cases the engine has seen before while running the bytecode. If we repeatedly used a certain piece of code that returned the &lt;em&gt;same&lt;/em&gt; data type over and over, the optimized machine code can simply be re-used in order to speed things up. However, since JavaScript is dynamically typed, it can happen that the same piece of code suddenly returns a different type of data. If that happens, the machine code gets de-optimized,  and the engine falls back to interpreting the generated byte code. &lt;/p&gt;

&lt;p&gt;Say a certain function is invoked a 100 times and has always returned the same value so far. It will &lt;em&gt;assume&lt;/em&gt; that it will also return this value the 101st time you invoke it. &lt;/p&gt;

&lt;p&gt;Let’s say that we have the following function sum, that’s (so far) always been called with numerical values as arguments each time:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fdhiaau4lo3n457yqud4o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fdhiaau4lo3n457yqud4o.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This returns the number &lt;code&gt;3&lt;/code&gt;! The next time we invoke it, it will assume that we’re invoking it again with two numerical values. &lt;/p&gt;

&lt;p&gt;If that’s true, no dynamic lookup is required, and it can just re-use the optimized machine code. Else, if the assumption was incorrect, it will revert back to the original byte code instead of the optimized machine code.&lt;/p&gt;

&lt;p&gt;For example, the next time we invoke it, we pass a string instead of a number. Since JavaScript is dynamically typed, we can do this without any errors! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fzugnjsg813urbj6vr4iy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fzugnjsg813urbj6vr4iy.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This means that the number &lt;code&gt;2&lt;/code&gt; will get coerced into a string, and the function will return the string  &lt;code&gt;"12"&lt;/code&gt; instead.  It goes back to executing the interpreted bytecode and updates the type feedback.&lt;/p&gt;




&lt;p&gt;I hope this post was useful to you! 😊 Of course, there are many parts to the engine that I haven't covered in this post (JS heap, call stack, etc.) which I might cover later! I definitely encourage you to start to doing some research yourself if you're interested in the internals of JavaScript, V8 is open source and has some great documentation on how it works under the hood! 🤖&lt;/p&gt;

&lt;p&gt;&lt;a href="https://v8.dev/" rel="noopener noreferrer"&gt;V8 Docs&lt;/a&gt; || &lt;a href="https://github.com/v8/v8" rel="noopener noreferrer"&gt;V8 Github&lt;/a&gt; || &lt;a href="https://www.youtube.com/watch?v=voDhHPNMEzg&amp;amp;t=729s&amp;lt;br&amp;gt;%0A" rel="noopener noreferrer"&gt;Chrome University 2018: Life Of A Script&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Feel free to reach out to me! &lt;strong&gt;&lt;a href="https://www.twitter.com/lydiahallie" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; || &lt;a href="https://www.instagram.com/theavocoder" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt; || &lt;a href="https://www.github.com/lydiahallie" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt; || &lt;a href="https://www.linkedin.com/in/lydia-hallie" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;FAQ: I use Keynote to make the animations and screen record it lol. Feel free to translate this blog to your language, and thanks so much for doing so! Just keep a reference to the original article and let me know if you've translated it please! 😊&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>computerscience</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>⚡️⛓JavaScript Visualized: Scope (Chain)</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Wed, 20 Nov 2019 07:12:21 +0000</pubDate>
      <link>https://dev.to/lydiahallie/javascript-visualized-scope-chain-13pd</link>
      <guid>https://dev.to/lydiahallie/javascript-visualized-scope-chain-13pd</guid>
      <description>&lt;p&gt;Time for the scope chain 🕺🏼 In this post I assume you know the basics of execution contexts: I’ll soon write a post on that too though 😃&lt;/p&gt;




&lt;p&gt;Let's take a look at the following code:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Lydia&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;21&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;city&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;San Francisco&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;


&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;getPersonInfo&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Sarah&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;22&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; is &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;age&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; and lives in &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;city&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;getPersonInfo&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We're invoking the &lt;code&gt;getPersonInfo&lt;/code&gt; function, which returns a string containing the values of the &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;age&lt;/code&gt; and &lt;code&gt;city&lt;/code&gt; variables:&lt;br&gt;
&lt;code&gt;Sarah is 22 and lives in San Francisco&lt;/code&gt;. But, the &lt;code&gt;getPersonInfo&lt;/code&gt; function doesn't contain a variable named &lt;code&gt;city&lt;/code&gt; 🤨? How did it know the value of &lt;code&gt;city&lt;/code&gt;? &lt;/p&gt;

&lt;p&gt;First, memory space is set up for the different contexts. We have the default &lt;strong&gt;global context&lt;/strong&gt; (&lt;code&gt;window&lt;/code&gt; in a browser, &lt;code&gt;global&lt;/code&gt; in Node), and a &lt;strong&gt;local context&lt;/strong&gt; for the &lt;code&gt;getPersonInfo&lt;/code&gt; function which has been invoked. Each context also has a &lt;strong&gt;scope chain&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;For the &lt;code&gt;getPersonInfo&lt;/code&gt; function, the scope chain looks something like this (don't worry, it doesn't have to make sense just yet):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F89b9buizhevs0jf6djyn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F89b9buizhevs0jf6djyn.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The scope chain is basically a "chain of references" to objects that contain references to values (and other scopes) that are referencable in that execution context. (⛓: "Hey, these are all the values you can reference from within this context".) The scope chain gets created when the execution context is created, meaning it's created at runtime! &lt;/p&gt;

&lt;p&gt;However, I won't talk about the &lt;em&gt;activation object&lt;/em&gt; or the execution contexts in general in this post, let's just focus on scope! In the following examples, the key/value pairs in the execution contexts represent the references that the scope chain has to the variables.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fiala2et7bg9bgdj4c2lg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fiala2et7bg9bgdj4c2lg.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The scope chain of the global execution context has a reference to 3 variables: &lt;code&gt;name&lt;/code&gt; with the value &lt;code&gt;Lydia&lt;/code&gt;, &lt;code&gt;age&lt;/code&gt; with the value &lt;code&gt;21&lt;/code&gt;, and &lt;code&gt;city&lt;/code&gt; with the value &lt;code&gt;San Francisco&lt;/code&gt;. In the local context, we have a reference to 2 variables: &lt;code&gt;name&lt;/code&gt; with the value &lt;code&gt;Sarah&lt;/code&gt;, and &lt;code&gt;age&lt;/code&gt; with the value &lt;code&gt;22&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;When we try to access the variables in the &lt;code&gt;getPersonInfo&lt;/code&gt; function, the engine first checks the local scope chain. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fxn17f0t54acz8tiq7122.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fxn17f0t54acz8tiq7122.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The local scope chain has a reference to &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;age&lt;/code&gt;! &lt;code&gt;name&lt;/code&gt; has the value of &lt;code&gt;Sarah&lt;/code&gt; and &lt;code&gt;age&lt;/code&gt; has the value of &lt;code&gt;22&lt;/code&gt;. But now, what happens when it tries to access &lt;code&gt;city&lt;/code&gt;? &lt;/p&gt;

&lt;p&gt;In order to find the value for &lt;code&gt;city&lt;/code&gt; the engine "goes down the scope chain". This basically just means that the engine doesn't give up that easily: it works hard for you to see if it can find a value for the variable &lt;code&gt;city&lt;/code&gt; in the outer scope that the local scope has a reference to, the &lt;strong&gt;global object&lt;/strong&gt; in this case.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fz9iclg23rmbpts7meoq6.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fz9iclg23rmbpts7meoq6.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the global context, we declared the variable &lt;code&gt;city&lt;/code&gt; with the value of &lt;code&gt;San Francisco&lt;/code&gt;, thus has a reference to the variable &lt;code&gt;city&lt;/code&gt;. Now that we have a value for the variable, the function &lt;code&gt;getPersonInfo&lt;/code&gt; can return the string &lt;code&gt;Sarah is 22 and lives in San Francisco&lt;/code&gt; 🎉&lt;/p&gt;




&lt;p&gt;We can go &lt;em&gt;down&lt;/em&gt; the scope chain, but we can't go &lt;em&gt;up&lt;/em&gt; the scope chain. (Okay this may be confusing because some people say &lt;em&gt;up&lt;/em&gt; instead of &lt;em&gt;down&lt;/em&gt;, so I'll just rephrase: You can go to &lt;strong&gt;outer&lt;/strong&gt; scopes, but not to more inner... (innerer..?) scopes. I like to visualize this as a sort of waterfall:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fdoq46yc6nuiam51evy44.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fdoq46yc6nuiam51evy44.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Or even deeper:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Frece2zj4pb4w1fn56q5k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Frece2zj4pb4w1fn56q5k.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Let's take this code as an example. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F0z6342b72f3n6v6ufafk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F0z6342b72f3n6v6ufafk.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It's almost the same, however there's one big difference: we &lt;em&gt;only&lt;/em&gt; declared &lt;code&gt;city&lt;/code&gt; in the &lt;code&gt;getPersonInfo&lt;/code&gt; function now, and &lt;em&gt;not&lt;/em&gt; in the global scope. We didn't invoke the &lt;code&gt;getPersonInfo&lt;/code&gt; function, so no local context is created either. Yet, we try to access the values of &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;age&lt;/code&gt; and &lt;code&gt;city&lt;/code&gt; in the global context.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ff3wvlo4c3gqf3mve1g0n.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ff3wvlo4c3gqf3mve1g0n.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It throws a &lt;code&gt;ReferenceError&lt;/code&gt;! It couldn't find a reference to a variable called &lt;code&gt;city&lt;/code&gt; in the global scope, and there were no outer scopes to look for, and it &lt;strong&gt;cannot&lt;/strong&gt; go &lt;em&gt;up&lt;/em&gt; the scope chain. &lt;/p&gt;

&lt;p&gt;This way, you can use scope as a way to "protect" your variables and re-use variable names.&lt;/p&gt;




&lt;p&gt;Besides global and local scopes, there is also a &lt;strong&gt;block scope&lt;/strong&gt;. Variables declared with the &lt;code&gt;let&lt;/code&gt; or &lt;code&gt;const&lt;/code&gt; keyword are scoped to the nearest curly brackets (&lt;code&gt;{&lt;/code&gt;&lt;code&gt;}&lt;/code&gt;).&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;21&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;checkAge&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;age&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;21&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;You cannot drink!&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;message&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;You can drink!&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;message&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; 


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can visualize the scopes as:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F75n1vpm7z4d8924cnvje.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F75n1vpm7z4d8924cnvje.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We have a global scope, a function scope, and two block scopes. We were able to declare the variable &lt;code&gt;message&lt;/code&gt; twice, since the variables were scoped to the curly brackets.&lt;/p&gt;




&lt;p&gt;To quickly recap:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You can see "scope chain" as a chain of references to values that we can access in the current context.&lt;/li&gt;
&lt;li&gt;Scopes also make it possible to re-use variable names that were defined further down the scope chain, since it can only go &lt;em&gt;down&lt;/em&gt; the scope chain, not &lt;em&gt;up&lt;/em&gt;. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That was it for scope (chains)! There's tons more to say about this so I may add extra info when I have some free time. Feel free to ask questions if you're struggling with anything, I love to help! 💕&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>tutorial</category>
      <category>webdev</category>
    </item>
    <item>
      <title>🔥🕺🏼 JavaScript Visualized: Hoisting</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Wed, 20 Nov 2019 07:12:16 +0000</pubDate>
      <link>https://dev.to/lydiahallie/javascript-visualized-hoisting-478h</link>
      <guid>https://dev.to/lydiahallie/javascript-visualized-hoisting-478h</guid>
      <description>&lt;p&gt;Hoisting is one of those terms that every JS dev has heard of because you googled your annoying error and ended up on StackOverflow, where this person told you that this error was caused because of &lt;em&gt;hoisting&lt;/em&gt; 🙃 So, what is hoisting? (FYI - &lt;em&gt;scope&lt;/em&gt; will be covered in another post, I like to keep posts small and focused)&lt;/p&gt;

&lt;p&gt;If you’re new to JavaScript, you may have experienced “weird” behavior where some variables are randomly &lt;code&gt;undefined&lt;/code&gt;, &lt;code&gt;ReferenceError&lt;/code&gt;s get thrown, and so on. Hoisting is often explained as &lt;em&gt;putting variables and functions to the top of the file&lt;/em&gt; but nah, that’s not what’s happening, although the behavior might seem like it 😃&lt;/p&gt;

&lt;p&gt;When the JS engine gets our script, the first thing it does is &lt;strong&gt;setting up memory&lt;/strong&gt; for the data in our code. No code is executed at this point, it’s simply just preparing everything for execution. The way that function declarations and variables are stored is different. Functions are stored with a &lt;strong&gt;reference to the entire function&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif7.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif7.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With variables, it’s a bit different. ES6 introduced two new keywords to declare variables: &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt;. Variables declared with the &lt;code&gt;let&lt;/code&gt; or &lt;code&gt;const&lt;/code&gt; keyword are stored &lt;em&gt;uninitialized&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif8.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif8.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Variables declared with the &lt;code&gt;var&lt;/code&gt; keyword are stored with the default value of &lt;code&gt;undefined&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif9.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif9.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that the creation phase is done, we can actually execute the code. Let's see what happens if we had 3 console.log statements on top of the file, before we declared the function or any of the variables.&lt;/p&gt;

&lt;p&gt;Since functions are stored with a reference to the entire function code,  we can invoke them even &lt;em&gt;before&lt;/em&gt; the line on which we created them! 🔥&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif16.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif16.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When we reference a variable declared with the &lt;code&gt;var&lt;/code&gt; keyword before their declaration, it’ll simply return its default value that it was stored with: &lt;code&gt;undefined&lt;/code&gt;! However, this could sometimes lead to "unexpected" behavior. In most cases this means you’re referencing it unintentionally (you probably don’t want it to actually have the value of &lt;code&gt;undefined&lt;/code&gt;) 😬&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif17.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif17.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In order to prevent being able to accidentally reference an &lt;code&gt;undefined&lt;/code&gt; variable, like we could with the &lt;code&gt;var&lt;/code&gt; keyword, a &lt;code&gt;ReferenceError&lt;/code&gt; gets thrown whenever we try to access &lt;em&gt;uninitialized&lt;/em&gt; variables. The "zone" before their actual declaration, is called the &lt;strong&gt;temporal dead zone&lt;/strong&gt;: you cannot reference the variables (this includes ES6 classes as well!) before their initialization.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif18.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif18.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When the engine passes the line on which we actually declared the variables, the values in memory are overwritten with the values we actually declared them with.&lt;/p&gt;

&lt;p&gt;(Oops I notice now this should be number 7. Will update asap 😬)&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif12.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif12.gif"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;All done! 🎉 Quick recap:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Functions and variables are stored in memory for an execution context before we execute our code. This is called &lt;em&gt;hoisting&lt;/em&gt;. &lt;/li&gt;
&lt;li&gt;Functions are stored with a reference to the entire functions, variables with the &lt;code&gt;var&lt;/code&gt; keyword with the value of &lt;code&gt;undefined&lt;/code&gt;, and variables with the &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; keyword are stored &lt;em&gt;uninitialized&lt;/em&gt;. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hope that the term &lt;em&gt;hoisting&lt;/em&gt; is a bit less vague now that we've looked at what's happening when we execute our code. As always, don't worry if it still doesn't make a lot of sense yet. You'll get a lot more comfortable with it the more you work with it. Feel free to ask me for help, I'd love to help you! 😃&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>✨♻️ JavaScript Visualized: Event Loop</title>
      <dc:creator>Lydia Hallie</dc:creator>
      <pubDate>Wed, 20 Nov 2019 07:12:11 +0000</pubDate>
      <link>https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif</link>
      <guid>https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif</guid>
      <description>&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/eiC58R16hb8"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;If you're here in 2024 (or later), here's an updated blog post!](&lt;a href="https://lydiahallie.com/blog/event-loop" rel="noopener noreferrer"&gt;https://lydiahallie.com/blog/event-loop&lt;/a&gt;)&lt;/p&gt;




&lt;p&gt;Oh boi the event loop. It’s one of those things that every JavaScript developer has to deal with in one way or another, but it can be a bit confusing to understand at first. I’m a visual learner so I thought I’d try to help you by explaining it in a visual way through low-res gifs because it's 2019 and gifs are somehow still pixelated and blurry. &lt;/p&gt;

&lt;p&gt;But first, what is the event loop and why should you care? &lt;/p&gt;

&lt;p&gt;JavaScript is &lt;strong&gt;single-threaded&lt;/strong&gt;: only one task can run at a time. Usually that’s no big deal, but now imagine you’re running a task which takes 30 seconds.. Ya.. During that task we’re waiting for 30 seconds before anything else can happen (JavaScript runs on the browser’s main thread by default, so the entire UI is stuck) 😬 It’s 2019, no one wants a slow, unresponsive website. &lt;/p&gt;

&lt;p&gt;Luckily, the browser gives us some features that the JavaScript engine itself doesn’t provide: a Web API. This includes the DOM API, &lt;code&gt;setTimeout&lt;/code&gt;, HTTP requests, and so on. This can help us create some async, non-blocking behavior 🚀&lt;/p&gt;

&lt;p&gt;When we invoke a function, it gets added to something called the call stack. The call stack is part of the JS engine, this isn’t browser specific. It’s a stack, meaning that it’s first in, last out (think of a pile of pancakes). When a function returns a value, it gets popped off the stack 👋&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgid1.6.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgid1.6.gif" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;respond&lt;/code&gt; function returns a &lt;code&gt;setTimeout&lt;/code&gt; function. The &lt;code&gt;setTimeout&lt;/code&gt; is provided to us by the Web API: it lets us delay tasks without blocking the main thread. The callback function that we passed to the &lt;code&gt;setTimeout&lt;/code&gt; function,  the arrow function &lt;code&gt;() =&amp;gt; { return&lt;/code&gt; &lt;code&gt;'&lt;/code&gt;&lt;code&gt;Hey&lt;/code&gt;&lt;code&gt;'&lt;/code&gt; } gets added to the Web API. In the meantime, the &lt;code&gt;setTimeout&lt;/code&gt; function and the respond function get popped off the stack, they both returned their values! &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif2.1.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif2.1.gif" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the Web API, a timer runs for as long as the second argument we passed to it, 1000ms.  The callback doesn’t immediately get added to the call stack, instead it’s passed to something called the queue. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif3.1.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif3.1.gif" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This can be a confusing part:  it doesn't mean that the callback function gets added to the callstack(thus returns a value) after 1000ms! It simply gets added to the &lt;em&gt;queue&lt;/em&gt; after 1000ms. But it’s a queue, the function has got to wait for its turn! &lt;/p&gt;

&lt;p&gt;Now this is the part we’ve all been waiting for… Time for the event loop to do its only task: &lt;strong&gt;connecting the queue with the call stack&lt;/strong&gt;! If the call stack is &lt;strong&gt;empty&lt;/strong&gt;, so if all previously invoked functions have returned their values and have been popped off the stack, the &lt;em&gt;first item&lt;/em&gt; in the queue gets added to the call stack. In this case, no other functions were invoked, meaning that the call stack was empty by the time  the callback function was the first item in the queue. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif4.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif4.gif" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The callback is added to the call stack, gets invoked, and returns a value, and gets popped off the stack. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif5.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif5.gif" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Reading an article is fun, but you'll only get entirely comfortable with this by actually working with it over and over. Try to figure out what gets logged to the console if we run the following:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;


&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;foo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;First&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;bar&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Second&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;baz&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Third&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nf"&gt;bar&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nf"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nf"&gt;baz&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Got it? Let's quickly take a look at what's happening when we're running this code in a browser:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif14.1.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdevtolydiahallie.s3-us-west-1.amazonaws.com%2Fgif14.1.gif" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We invoke &lt;code&gt;bar&lt;/code&gt;. &lt;code&gt;bar&lt;/code&gt; returns a &lt;code&gt;setTimeout&lt;/code&gt; function.&lt;/li&gt;
&lt;li&gt;The callback we passed to &lt;code&gt;setTimeout&lt;/code&gt; gets added to the Web API, the &lt;code&gt;setTimeout&lt;/code&gt; function and &lt;code&gt;bar&lt;/code&gt; get popped off the callstack. &lt;/li&gt;
&lt;li&gt;The timer runs, in the meantime &lt;code&gt;foo&lt;/code&gt; gets invoked and logs &lt;code&gt;First&lt;/code&gt;. &lt;code&gt;foo&lt;/code&gt; returns (undefined),&lt;code&gt;baz&lt;/code&gt; gets invoked, and the callback gets added to the queue.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;baz&lt;/code&gt; logs &lt;code&gt;Third&lt;/code&gt;. The event loop sees the callstack is empty after &lt;code&gt;baz&lt;/code&gt; returned, after which the callback gets added to the call stack.&lt;/li&gt;
&lt;li&gt;The callback logs &lt;code&gt;Second&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Hope that this makes you feel a bit more comfortable with the event loop! Don't worry if it still seems confusing, the most important thing is to &lt;strong&gt;understand where certain errors/behavior can come from&lt;/strong&gt; in order to &lt;strong&gt;Google the right terms efficiently&lt;/strong&gt; and end up on the correct Stack Overflow page 💪🏼 Feel free to reach out to me if you have any questions!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
