<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Javascript &#8211; Chris Philbin&#039;s Blog</title>
	<atom:link href="https://www.chrisphilbin.net/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.chrisphilbin.net</link>
	<description>Perfection Through Persistence.</description>
	<lastBuildDate>Thu, 15 Aug 2024 01:23:47 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.2</generator>
	<item>
		<title>Javascript&#8217;s Temporal Dead Zone (TDZ)</title>
		<link>https://www.chrisphilbin.net/javascripts-temporal-dead-zone-tdz/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 15 Aug 2024 01:12:43 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://www.chrisphilbin.net/?p=544</guid>

					<description><![CDATA[Not to be confused with the &#8220;temporal pincer movement&#8221; from Christopher Nolan&#8217;s 2020 movie Tenet, but perhaps equally confusing, is the concept in Javascript known as the Temporal Dead Zone,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Not to be confused with the &#8220;temporal pincer movement&#8221; from Christopher Nolan&#8217;s 2020 movie Tenet, but perhaps equally confusing, is the concept in Javascript known as the Temporal Dead Zone, or the TDZ.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img fetchpriority="high" decoding="async" width="931" height="561" src="https://www.chrisphilbin.net/wp-content/uploads/2024/08/tdz.webp" alt="" class="wp-image-551" style="width:577px;height:auto" srcset="https://www.chrisphilbin.net/wp-content/uploads/2024/08/tdz.webp 931w, https://www.chrisphilbin.net/wp-content/uploads/2024/08/tdz-300x181.webp 300w, https://www.chrisphilbin.net/wp-content/uploads/2024/08/tdz-768x463.webp 768w" sizes="(max-width: 931px) 100vw, 931px" /><figcaption class="wp-element-caption">Neil trying to explain the Temporal Dead Zone</figcaption></figure></div>


<p>To put it simply, the TDZ is a phase in a variable&#8217;s lifecycle where it <em>technically exists</em>, however it cannot be accessed or used &#8211; This phenomenon mostly applies to variables defined with the keyword <strong>let</strong> or <strong>const</strong>, but not <strong>var</strong> (And function definitions, too), thanks to the concept of hoisting (More on &#8216;hoisting&#8217; in a moment &#8211; there are a few caveats, which is why I said &#8216;mostly&#8217;).</p>



<p>Let&#8217;s take a look at a contrived example to see the TDZ in action:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function myFunction() {
    console.log(x);
    let x = &quot;Hello, world!&quot;;
}

myFunction();
</pre></div>


<p>The above will result in the following being logged to the JS console:</p>



<pre class="wp-block-code"><code>ReferenceError: Cannot access 'x' before initialization</code></pre>



<p>The JS interpreter knows that x exists, however it cannot access it before it&#8217;s been initialized &#8211; x is in the temporal dead zone. Think of it this way: You&#8217;re going to make a dish that requires bread crumbs. You can see through the clear doors of the cabinet that you have bread crumbs available, but you cannot physically touch them until the doors have been opened. You know they exist, but you just can&#8217;t get to them yet. They too are in the temporal dead zone.</p>



<p>Let&#8217;s take a look at the same example from above, but using the <strong>var</strong> keyword to handle the variable declaration:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function myFunction() {
    console.log(x);
    var x = &quot;Hello, world!&quot;;
}

myFunction();
</pre></div>


<p>The above works&#8230; Kind of. <strong>Undefined</strong> is logged to the console, indicating that x has been initialized, but has yet to be assigned any value. Interesting. Now is a good time to touch on the concept of hoisting.</p>



<p>In JS, hoisting is the concept where all variables (Those declared using var, let, and const) and function declarations get &#8220;hoisted&#8221; (think: &#8220;pulled to the top&#8221;) of the current scope. Note how I said declarations &#8211; NOT assignments.</p>



<p>Variables defined with <strong>var</strong> can be accessed before they are initialized, and they can be re-declared in the same scope, whereas variables defined with <strong>let </strong>and <strong>const</strong> cannot be accessed before they are initialized (They too are hoisted, but they are in the TDZ), and they cannot be re-declared in the same scope.</p>



<p>This is why in the last example from above where using <strong>var</strong> resulted in undefined being returned and not a ReferenceError like in the <strong>let</strong> example. x was declared, however it was not assigned any value, hence it was undefined.</p>



<p>So variables declared with the keyword <strong>var</strong> can be &#8220;used&#8221; before they&#8217;re actually assigned a value, just expect them to return undefined until they are actually assigned a value, whereas variables defined with <strong>let</strong> and <strong>const</strong> will result in a ReferenceError since they live in the temporal dead zone.</p>



<p>So why is the TDZ a thing when it comes to variables defined with either <strong>let</strong> or <strong>const</strong>?</p>



<p>Both <strong>let </strong>and <strong>const</strong> were introduced in 2015 with ES6, and the concept of the TDZ was born in order to enhance code readability and enforce some level of standardization by encouraging developers to initialize and define variables at the same time. <strong>var </strong>still exists because backwards compatibility needed to be kept in mind so older code didn&#8217;t break. As of 2024, <strong>let </strong>and <strong>const </strong>are the preferred key words to use when defining a variable.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Building the Javascript .map() function from scratch</title>
		<link>https://www.chrisphilbin.net/building-the-javascript-map-function-from-scratch/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Fri, 01 Sep 2023 19:51:39 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=283</guid>

					<description><![CDATA[Probably one of the most used and most powerful functions ( .reduce() might be the most important) in the Javascript language is the .map() function (And let&#8217;s not forget it&#8217;s&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Probably one of the most used and most powerful functions ( .reduce() might be <em>the</em> most important) in the Javascript language is the .map() function (And let&#8217;s not forget it&#8217;s somewhat closely related cousin .forEach()). Both of these functions allow us to iterate over an array and do something with each element one by one.</p>



<p><strong>First, what is the difference between map and forEach in Javascript?</strong></p>



<p>.map() &#8211; Iterates over a collection and does <em>something</em> to each item and then pushes that new element to a newly created array which is then returned once each element in the provided collection has been iterated over.</p>



<p>.forEach() &#8211; Still iterates over a collection and does <em>something</em> to each item but it does not push the returned value of the action to a new array. (Think: &#8220;for each element in this array, go off an fire of an XHR and get the response and do something with it&#8221;&#8230; Have fun with all of the promises!) </p>



<p><strong>Let&#8217;s recreate .map() from scratch</strong></p>



<p>When writing software we take for granted what is going on under the hood in the built in methods and functions Javascript provides to us (Really any language, for that matter). By re-creating .map() from scratch will give us a better understanding of how the code is behaving in our applications. From there we can start building on that knowledge to understand more advanced topics like how the reduce function works.</p>



<p>Remember: .map() allows us to go through each element in a collection (array) and does something to each element (it &#8216;maps it&#8217; to a new value based on the instructions we give it) and then returns an array with all the new values.</p>



<p>A few things stick out right away with the above breakdown:</p>



<ul class="wp-block-list">
<li>Our custom map function will have two parameters:
<ul class="wp-block-list">
<li>The input collection (array)</li>



<li>Instructions (a callback function) that we pass in</li>
</ul>
</li>



<li>Our custom map function will also need a way to iterate over each element &#8211; So we&#8217;ll have to employ some kind of loop to achieve this</li>



<li>We&#8217;re returning a new array &#8211; at some point we&#8217;re going to have to create a new array</li>
</ul>



<p>Ready? Here&#8217;s essentially what map is doing under the hood:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const arr = &#x5B;1, 2, 3, 4, 5];

const newMap = (input, mutator) =&gt; {
  let newArr = &#x5B;];
  for (let i = 0; i &lt; input.length; i++) {
    newArr.push(mutator(input&#x5B;i]));
  }
  return newArr;
};
const multiplyByTwo = (num) =&gt; {
  return num * 2;
};

const answer = newMap(arr, multiplyByTwo);

console.log(answer);
</pre></div>


<p>Line 1 we&#8217;re declaring a constant in memory with the label <strong>arr</strong> and assigning it the value [1, 2, 3, 4, 5].</p>



<p>Line 3 we&#8217;re defining a function in memory with the label <strong>newMap</strong>.</p>



<p>Line 10 we&#8217;re again defining a function in memory with the label <strong>multiplyByTwo</strong>.</p>



<p>And finally, line 14 we are declaring a constant in memory and assigning it the value to <strong>whatever the code to the right of the equals sign evaluates to &#8211; this is where we invoke/run the code above</strong>.</p>



<p>To the right of the equals sign on line 14 we run the newMap function and we provide it with two arguments: arr and the function multiplyByTwo.</p>



<p>We then create a new local execution context when we start running the newMap function where we setup our parameters:</p>



<p><strong>input</strong>: [1, 2, 3, 4, 5]<br><strong>mutator</strong>: (num) =&gt; { return num * 2 }</p>



<p>Next, we create a new empty array giving it the label <strong>newArr</strong>.</p>



<p>The provided array, now known as <em>input</em> in this local execution context, is then iterated over using a for loop. For each element in the collection, we then run the multiplyByTwo function with the input, which then returns the input number multiplied by 2 and that number is then pushed into the previously created new blank array (<strong>newArr</strong>).</p>



<p>Finally, once the for loop completes, the function then runs the last line of code which is to &#8220;spit out&#8221; (return) the newly created array and store that into the variable <strong>answer</strong> where we then console.log it to see it&#8217;s value.</p>



<p><strong>Closing thoughts</strong></p>



<p>Recreating the map function is a great exercise for newer developers because it allows you to &#8220;peel back the layers&#8221; of what&#8217;s going on under the hood in some of the code you&#8217;ve been working with for several months or years. Furthermore, doing this also gives you a better understanding of how functional programming in Javascript works and by understanding how .map() works under the hood you will have a much better understanding of how .reduce() is working which is the cornerstone of functional programming.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Demystifying the new keyword in Javascript</title>
		<link>https://www.chrisphilbin.net/javascript-new-keyword/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 26 Aug 2023 11:48:12 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=292</guid>

					<description><![CDATA[Javascript&#8217;s &#8216;new&#8217; keyword goes hand-in-hand with the object oriented programming paradigm in which the code written aims to mimic things and actions in the real world. A dog can run&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Javascript&#8217;s &#8216;new&#8217; keyword goes hand-in-hand with the object oriented programming paradigm in which the code written aims to mimic things and actions in the real world. A dog can run and jump, a user can login and logout. In the world of Javascript, a single &#8216;dog&#8217; would be an object, and the &#8216;run&#8217; action would be a method found on that object.</p>



<p>Object oriented programming seeks to combine data and actions that we can invoke on that data while making it easy for us programmers to switch between the two.</p>



<p>Consider the following scenario: We have a user and that user wants to login to our eCommerce app, browse around, place an order and perhaps leave a review for a product they purchased several weeks ago. </p>



<p>First, let&#8217;s take a look at a naive approach that you will see very quickly will not scale well and will lead to a lot of memory usage:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const user1 = {
    userId: &quot;00001&quot;,
    name: &quot;Thomas&quot;,
    displayName: &quot;tom123&quot;,
    email: &quot;thomas.smith@example.com&quot;,
    login: () =&gt; {
        //login business logic
        //maybe an API call, storing session info
        console.log(&quot;User has successfully logged in!&quot;)
    },
    logout: () =&gt; {
        //logout business logic
        //Another API call, removing session info
        console.log(&quot;User has successfully logged out!&quot;)
    }
}

console.log(user1.displayName) //returns &#039;tom123&#039;
user1.login() //logs the user in to the app
</pre></div>


<p>The above code is fairly straightforward. We create an object with several properties (userId, name, etc) and assigned it the label &#8216;user1&#8217; in memory. This also has a few methods attached as well: login and logout.</p>



<p>The object oriented &#8216;litmus test&#8217; is: <em>Can we run user1.login() and actually access both the object and the functionality that we want?</em></p>



<p>While the answer is &#8216;yes&#8217; for the above sample, it has several fairly obvious issues:</p>



<p>What if we have 100 users, or perhaps 100,000 users or even more? Every single user object will have to have copies of those two login and logout methods and waste a lot of memory in the process. Also, what if we have to change the business logic in either of those methods sometime in the future due to some enhancements the product team wants? You would be stuck trying to individually update thousands and thousands of methods and hope for no errors along the way.</p>



<p>This implementation will not scale well, however at its core this is exactly what we want in terms of features &#8211; it satisfied the object oriented litmus test of &#8216;Can we run user1.login() and actually access both the object and the functionality that we want?&#8217;</p>



<p>Let&#8217;s take a look at another implementation that uses Object.create() &#8211; Object.create(), if invoked without any arguments will return a blank object. If passed an argument that is itself an object with key/value pairs, it will do something pretty interesting that gets us pretty close to our ideal solution to implement an object oriented programming paradigm in Javascript.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const userFunctions = {
  login: () =&gt; {
    //login business logic
    //maybe an API call, storing session info
    console.log(&quot;User has successfully logged in!&quot;);
  },
  logout: () =&gt; {
    //logout business logic
    //Another API call, removing session info
    console.log(&quot;User has successfully logged out!&quot;);
  },
};

const user2 = Object.create(userFunctions);

console.log(user2.__proto__, &quot;user2 proto&quot;);

user2.userId = &quot;00002&quot;;
user2.name = &quot;Sam&quot;;
user2.displayName = &quot;Sam123&quot;;
user2.email = &quot;sam@example.com&quot;;

user2.login();
</pre></div>


<p>When we <strong>console.log(user2.__proto__)</strong> we get to see the magic that is going on behind the scenes. Javascript will append an __proto__ (double underscore proto, sometimes called &#8216;dunder proto&#8217;) to each object and it will then in turn give access to the login and logout functions. The litmus test holds true: When we call user2.login() Javascript looks to the __proto__ property when it doesn&#8217;t find the login() method immediately on user2. Once it finds it, it then invokes login() and the body of the function then runs.</p>



<p>Finally, we can clean this up a little further and utilize some more modern ES2015 features: The &#8216;new&#8217; keyword.</p>



<p>The &#8216;new&#8217; keyword in Javascript automates 3 key tasks for us:</p>



<ol class="wp-block-list">
<li>It auto-creates an empty object and assigns it to the label &#8216;this&#8217;</li>



<li>It sets up a hidden __proto__ property that points to the constructor function&#8217;s prototype object that contains all of the desired functionality</li>



<li>It automatically returns the newly created object that was stored in the &#8216;this&#8217; label in memory.</li>
</ol>



<p>Let&#8217;s see it in action:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function CreateUser(userId, name, displayName, email) {
  this.userId = userId;
  this.name = name;
  this.displayName = displayName;
  this.email = email;
}

CreateUser.prototype.login = function () {
  console.log(&quot;User has successfully logged in!&quot;);
};

CreateUser.prototype.logout = function () {
  console.log(&quot;User3 has successfully logged out!&quot;);
};

const user3 = new CreateUser(&quot;00003&quot;, &quot;Mike&quot;, &quot;Mike123&quot;, &quot;mike@example.com&quot;);

console.log(user3.__proto__, &quot;user3 __proto__&quot;);

user3.login();
</pre></div>


<p>In this example, user3.__proto__ points to the prototype object on the CreateUser function &#8211; this happens thanks in part to the &#8216;new&#8217; keyword. This functionality is made possible because when you create a function in memory, not only does Javascript save the function body, but it also creates a &#8216;hidden&#8217; object that you can append key/value pairs to. This concept is sometimes referred to as a &#8220;function object combo&#8221;.</p>



<p>Javascript takes the above concepts even one step further by implementing classes, however that topic is better left for another article for another time. Thanks for reading and hopefully you&#8217;ve gained a better understanding of how the &#8216;new&#8217; keyword is working under the hood!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The Differences Between Subjects and BehaviorSubjects in RxJS</title>
		<link>https://www.chrisphilbin.net/the-differences-between-subjects-and-behaviorsubjects-in-rxjs/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 16 Aug 2023 23:59:00 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[RxJS]]></category>
		<category><![CDATA[Typescript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=315</guid>

					<description><![CDATA[If you&#8217;re just starting to dive into Angular you&#8217;ve probably quickly realized that it&#8217;s a lot different from the other major front end frameworks such as React and Vue. Angular&#8230;]]></description>
										<content:encoded><![CDATA[
<p>If you&#8217;re just starting to dive into Angular you&#8217;ve probably quickly realized that it&#8217;s a lot different from the other major front end frameworks such as React and Vue. Angular is a &#8220;convention over configuration&#8221; framework in the sense that the Angular development team has designed the framework in such a way to more or less <em>force</em> you into following a certain set of rules in order for it to work properly. (I&#8217;ve personally found Vue to be a happy medium in between Angular and React in this sense)</p>



<p>If you&#8217;re a less experienced front end developer and are looking to up your JavaScript game, forcing yourself to create a few Angular apps is a great way to really level up your JS skill set. React and Vue do a great job at abstracting things away so some things that happen just seem like magic. Angular still has abstractions however not to the extent of the other two so you&#8217;re forced to roll up your sleeves and up your JS game. (This is really just me saying the learning curve for Angular is more demanding that any other front end framework.)</p>



<p>Angular ships with RxJS and it&#8217;s a complete paradigm shift in that you no longer simply rely on fetch() or axios.get() to handle your HTTP requests in your app. RxJS instead allows us as developers to <em>subscribe</em> to a data stream and listen to it for any changes while the subscription is active. To be fair, you can implement RxJS in either a React or Vue app, but neither ships with it out of the box so it&#8217;s up to you the install it as a dependency and use it (Convention over configuration&#8230; Remember?)</p>



<p>Subjects and BehaviorSubjects are observables that can emit their values to multiple observers via subscriptions. On the surface we&#8217;re almost inclined to think that both a Subject and a BehaviorSubject do the same thing, but the differences are subtle and can make a pretty big impact on your application.</p>



<p>In simple terms: <strong>A Subject does not need to have an initial value when being created but a BehaviorSubject requires an initial value when being created.</strong> Therefore, a Subject will only emit upcoming values, whereas a BehaviorSubject will emit <em>one previous value and all upcoming values</em>.</p>



<p>Let&#8217;s set the stage for a pretty common example front end developers handle on a routine basis: showing or hiding a modal to let the user edit settings. As you can imagine, this is a good use case for a BehaviorSubject because we&#8217;ll want to set the initial value of &#8220;showModal&#8221; to &#8220;false&#8221;.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
// src/app/services/modal.service.ts

import { BehaviorSubject } from &#039;rxjs&#039;;

export class ModalService {
  showModal = new BehaviorSubject&lt;boolean&gt;(false);

  toggleModal() {
    this.showModal.next(!this.showModal.value);
  }
}
</pre></div>


<p>Had we not passed in a boolean value to the BehaviorSubject&#8217;s constructor, TypeScript would have immediately given us an error indicating that one argument was expected, but we&#8217;ve given it 0.</p>



<p>The above example sets up an Angular service that we can then import into any other component and utilize the toggleModal() method. Any subscriptions to this observable therefore will receive an initial value of &#8220;false&#8221; since BehaviorSubjects allow us to track and initial value and any subsequent changes in the future.</p>



<p>On the other hand, a Subject does not require an initial value. In sticking with the modal example from above, a good parallel use case for a Subject would be if upon the user opening a modal in the app we want to display a form containing the app&#8217;s settings that they can modify and then save. Let&#8217;s take a look:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
// src/app/services/settings.service.ts

import { Subject } from &#039;rxjs&#039;;
import { HttpClient } from &#039;@angular/common/http&#039;;

export class SettingsService {

  appSettings = new Subject&lt;Settings&gt;();

  constructor(private http: HttpClient) {}

  getAppSettings() {
  this.http.get&lt;Settings&gt;(&#039;https://www.myapp_api.com/settings&#039;)
    .subscribe((settings: Settings) =&gt; {
      console.log(settings, &#039;Settings received from API call.&#039;);
      this.settings.next(settings);
    )};
  }

}
</pre></div>


<p>Sure, there&#8217;s a little more code than the previous BehaviorSubject example but most of it is simply boiler plate code in order to set things up. The key takeaway here should be that when we create a new Subject, we do not have to supply its constructor method with an argument to set the initial value upon creation. We only have to indicate what kind of value will be occupying it in the future, which in this case is an object of type &#8220;Settings&#8221;.</p>



<p>We&#8217;ve defined a getAppSettings() method that we can again import into any other component and fetch our user&#8217;s app settings from the back end and then once the request comes back we will push the new value via the next() method and any subscriptions made will finally receive their first value. We will then have access to the app settings, now stored with the label <strong>appSettings</strong>, be it an object of settings or an array.</p>



<p>So what&#8217;s the tl;dr version of all of this? Pretty simple, actually:</p>



<p><strong>Use a BehaviorSubject if you need an initial value (The modal example above is a really good example) and use a Subject if you do not need an initial value.</strong></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>JavaScript closures: What are they?</title>
		<link>https://www.chrisphilbin.net/javascript-closures-what-are-they/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 02 Aug 2023 10:54:00 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=390</guid>

					<description><![CDATA[A closure in JavaScript is a pretty obscure concept to grasp, especially when starting out. They&#8217;re one of the more important building blocks and concepts in JS that enable many&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A closure in JavaScript is a pretty obscure concept to grasp, especially when starting out. They&#8217;re one of the more important building blocks and concepts in JS that enable many other features in the language to work. (Like iterators and generators, and even paves the way for concepts like observable streams)</p>



<p>From<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures"> MDN</a>, a closure is as follows:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>A&nbsp;<strong>closure</strong>&nbsp;is the combination of a function bundled together (enclosed) with references to its surrounding state (the&nbsp;<strong>lexical environment</strong>). In other words, a closure gives you access to an outer function&#8217;s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</p>
<cite>https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures</cite></blockquote>



<p>Essentially, we can think of a closure as a <strong><em>backpack</em></strong> that every function gets whenever it is defined. The contents of said backpack are dependent on where the function was defined &#8211; this is also known as its <strong><em>scope</em></strong>. This is what we mean when something is <strong><em>lexically scoped</em></strong>. In this backpack we will find the surrounding function&#8217;s variables, which will allow the inner function (the one that is carrying the backpack) to have access to the outer function&#8217;s scope/variables even after it&#8217;s finished executing. We can really start to leverage this feature of JavaScript when we return a function from another function.</p>



<p>Let&#8217;s take a look at a really basic example to get a better understanding at how this concept works in practice:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function outerFunc() {
  let counter = 0;

  return function innerFunc() {
    console.log(`The value of counter is: ${counter}`);
    counter++;
  };
}

const runnerFunc = outerFunc();

runnerFunc();
runnerFunc();
runnerFunc();
runnerFunc();
runnerFunc();
runnerFunc();
</pre></div>


<p>And the output that&#8217;s logged to the console is:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
The value of counter is: 0
The value of counter is: 1
The value of counter is: 2
The value of counter is: 3
The value of counter is: 4
The value of counter is: 5
</pre></div>


<p>Line 6 from the code example above (Not the console.log output) is extremely important &#8211; <strong><em>the inner function is incrementing a variable that was defined in the outer function&#8217;s scope</em></strong>. When running functions, we&#8217;re used to them <strong>not</strong> being able to persist the variables/state from its previous execution context (the last time it was run), but somehow in this example the inner function was still able to access variables that belonged to the outer function&#8217;s scope even after it was finished running! Enter the concept of closures!</p>



<p>We can do some really interesting things with this newly found knowledge. Let&#8217;s take another look at a custom made generator function that we can pull values from one at a time. This is a big paradigm shift in that we normally iterate over a collection of objects and get the value one at a time that way using a tried and true for or while loop. Let&#8217;s have a look:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function countUpUntil(x) {
  let counter = 0;
  function next() {
    if (counter &lt;= x) {
      return { value: counter++, done: false };
    }
    return { value: undefined, done: true };
  }

  return { next };
}

const iterator = countUpUntil(5);

console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(interator.next());
</pre></div>


<p>And let&#8217;s have a look at the output from the console:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
{ value: 0, done: false }
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: 4, done: false }
{ value: 5, done: false }
{ value: undefined, done: true }
</pre></div>


<p>Now we&#8217;ve created a function in such a way that will only allow us to run it a certain amount of times! We can use this method to enable us to &#8220;pull&#8221; from a collection each time the function is run as opposed to us traversing the entire collection using a traditional for/while loop &#8211; an incredible paradigm shift that paves the way for concepts like observable streams, generator functions, and iterator functions, all of which are significant building blocks in the JavaScript ecosystem. </p>



<p>In the above code example, we again have an inner function, this time called <strong><em>next</em></strong>, that is accessing the variable with the label <strong><em>counter</em></strong> that was defined in the outer function&#8217;s execution context. In fact, we reference counter twice &#8211; we perform a conditional to see if counter is less than or equal to x (the number we want to &#8216;count&#8217; up until), and if the conditional is true, we then return an object that contains the value of count after it&#8217;s been incremented by 1, as well as a boolean letting us know whether or not the stream is done. When the conditional returns false, we get an object back with a value of undefined, and a truthy value for done letting us know the stream has finished giving us results. We can then implement logic elsewhere in our program to check for the truthy value.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Using JavaScript to validate parentheses</title>
		<link>https://www.chrisphilbin.net/using-javascript-to-validate-parentheses/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 09 Mar 2023 13:51:48 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=359</guid>

					<description><![CDATA[Let&#8217;s explore how we can use JavaScript to determine whether or not a string containing parentheses, square brackets, and/or curly braces has an equal number of opening and closing brackets/braces.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Let&#8217;s explore how we can use JavaScript to determine whether or not a string containing parentheses, square brackets, and/or curly braces has an equal number of opening and closing brackets/braces. Essentially we&#8217;re going to determine if a string such as <strong>(){}[]</strong> is valid.</p>



<p>Essentially, each opening bracket or brace needs to have a corresponding closing bracket or brace. </p>



<p>First, let&#8217;s take a look at the code in its entirety:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const isValid = (s) =&gt; {
    const remaining = &#x5B;];
    const legend = {
        &quot;(&quot; : &quot;)&quot;,
        &quot;{&quot; : &quot;}&quot;,
        &quot;&#x5B;&quot; : &quot;]&quot;,
    };
    
    for (let i = 0; i &lt; s.length; i++) {
        if (s&#x5B;i] === &quot;(&quot; || s&#x5B;i] === &quot;{&quot; || s&#x5B;i] === &quot;&#x5B;&quot;) {
            remaining.push(s&#x5B;i])
        } else if (legend&#x5B;remaining.pop()] !== s&#x5B;i]) {
            return false;
        }
    }
    return remaining.length ? false : true;
};

isValid(&quot;()&#x5B;]{}&quot;);
</pre></div>


<p>We begin by defining an empty array that is going to serve as a &#8220;pseudo stack&#8221; in which we are pushing/popping elements from as we traverse the given string. We also define a legend object, which is simply a key/value collection of each opening bracket/brace and its associated closing element.</p>



<p>We will utilize a traditional for loop that will traverse the input string and within each iteration of the loop we will perform two checks:</p>



<ol class="wp-block-list">
<li>If the current character of the input string <strong>s[i]</strong> is equal to any opening bracket/brace we will push it into the remaining array.</li>



<li>Else, if the last character from the remaining array DOES NOT equal the current character, we return false;</li>
</ol>



<p>If the second condition is never encountered, we reach the end of the string and then do one final comparison where we look to see if there are any remaining elements in the array. If so, we return false. This last check essentially checks for any orphaned brackets that might have resulted from the input string be an odd length.</p>



<p>One possible alternative solution to this last check is to do the odd check at the very start of the function and immediately return false if the length is determined to be odd. If this is the case, we can safely assume that at least one bracket/brace doesn&#8217;t have a valid closing bracket/brace. It would look like this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
const isValid = (s) =&gt; {
    if (s.length % 2 !== 0) return false;
    const remaining = &#x5B;];
    const legend = {
        &quot;(&quot; : &quot;)&quot;,
        &quot;{&quot; : &quot;}&quot;,
        &quot;&#x5B;&quot; : &quot;]&quot;,
    };
    
    for (let i = 0; i &lt; s.length; i++) {
        if (s&#x5B;i] === &quot;(&quot; || s&#x5B;i] === &quot;{&quot; || s&#x5B;i] === &quot;&#x5B;&quot;) {
            remaining.push(s&#x5B;i])
        } else if (legend&#x5B;remaining.pop()] !== s&#x5B;i]) {
            return false;
        }
    }
    return true;
};

isValid(&quot;()&#x5B;]{}&quot;);
</pre></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Implementing a word cloud with React</title>
		<link>https://www.chrisphilbin.net/implementing-a-word-cloud-with-react/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Fri, 10 Feb 2023 11:08:00 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=354</guid>

					<description><![CDATA[I actually had this come up as an interview question once, and it was more of a theoretical discussion on how I would implement it, as opposed to actually having&#8230;]]></description>
										<content:encoded><![CDATA[
<p>I actually had this come up as an interview question once, and it was more of a theoretical discussion on <em>how</em> I would implement it, as opposed to actually having me white board it/live code it. I thought it would be good practice to re-visit this and implement a quick solution.</p>



<p>I opted to create a helper function that takes an object that contains the word itself, as well as the count &#8211; or frequency &#8211; that each word appears. The function simply returns a string based on whether or not certain conditions are made. For example, if the word count is less than or equal to 4, it will return the string &#8220;small&#8221;. We can then use that to set the fontSize to &#8220;small&#8221;. Let&#8217;s take a look at the code:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
import React from &quot;react&quot;;
import &quot;./word-cloud.styles.css&quot;;

const WordCloud = () =&gt; {
  const words = &#x5B;
    { word: &quot;car&quot;, count: 3 },
    { word: &quot;electric&quot;, count: 8 },
    { word: &quot;engine&quot;, count: 5 },
    { word: &quot;motor&quot;, count: 11 },
    { word: &quot;brake&quot;, count: 1 },
  ];

  const applyStyling = ({ word, count }) =&gt; {
    if (count &lt;= 2) {
      return &quot;x-small&quot;;
    } else if (count &lt;= 4) {
      return &quot;small&quot;;
    } else if (count &lt;= 6) {
      return &quot;medium&quot;;
    } else if (count &lt;= 8) {
      return &quot;large&quot;;
    } else if (count &gt;= 9) {
      return &quot;x-large&quot;;
    } else {
      return &quot;medium&quot;;
    }
  };

  return (
    &lt;div className=&quot;main-div&quot;&gt;
      {words.map((word, index) =&gt; (
        &lt;li key={index} className=&quot;word-list-item&quot;&gt;
          &lt;p style={{ fontSize: applyStyling(word) }}&gt;{word.word}&lt;/p&gt;
        &lt;/li&gt;
      ))}
    &lt;/div&gt;
  );
};

export default WordCloud;
</pre></div>


<p>I opted to go with in-line styling for this specific example instead of creating many classes that each set the font-size property to the proper values. If you wanted to implement a CSS class-based implementation, instead of a style attribute, you&#8217;d utilize the className attribute, and assign the returned value from the applyStyling function to that.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Vue: Computed properties vs. watcher</title>
		<link>https://www.chrisphilbin.net/vue-computed-properties-vs-watcher/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Mon, 06 Feb 2023 17:25:30 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Vue]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=346</guid>

					<description><![CDATA[Vue.js, or just Vue for short, is one of the big three main JavaScript front end libraries (The other two being React and Angular). In my opinion, Vue is a&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Vue.js, or just Vue for short, is one of the big three main JavaScript front end libraries (The other two being React and Angular). In my opinion, Vue is a nice middle ground between React and Angular in terms of the learning curves associated with learning and implementing the framework, as well as how many implementation/configuration decisions need to be made by the developer. </p>



<p>Two of the main building blocks when creating a Vue component are <strong>computed properties</strong>, as well as <strong>watchers</strong>. Initially, both seem to be very similar, but a few quick examples of their suggested use cases will quickly clear up what a computed property is best suited for, and what a watcher is best suited for.</p>



<p>First, per the Vue documentation, let&#8217;s check out their definitions:</p>



<p></p>



<h2 class="wp-block-heading">Computed Property </h2>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><em>A computed property is used to declaratively describe a value that depends on other values. When you data-bind to a computed property inside the template, Vue knows when to update the DOM when any of the values depended upon by the computed property has changed. This can be very powerful and makes your code more declarative, data-driven and thus easier to maintain.</em></p>
<cite><a href="https://012.vuejs.org/guide/computed.html" target="_blank" rel="noreferrer noopener">Vue.js documentation</a></cite></blockquote>



<h2 class="wp-block-heading">Watcher</h2>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>While computed properties are more appropriate in most cases, there are times when a custom watcher is necessary. That’s why Vue provides a more generic way to react to data changes through the&nbsp;<code>watch</code>&nbsp;option. This is most useful when you want to perform asynchronous or expensive operations in response to changing data.</p>
<cite><a href="https://v2.vuejs.org/v2/guide/computed.html#Watchers">Vue.js documentation</a></cite></blockquote>



<p>One of the best examples to show what a computed property is best used for is to create a method that formats names that you get from either props that are being passed in, or fetched from an external API call. Let&#8217;s take a look at a simple example where we rely on an API response to get the names of all super heros:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
&lt;!-- COMPUTED PROPERTY EXAMPLE --&gt;
&lt;template&gt;
  &lt;div v-if=&quot;formattedSuperHeroNames.length&quot;&gt;
    &lt;li v-for=&quot;hero in formattedSuperHeroNames&quot; :key=&quot;hero.id&quot;&gt;{{ hero.heroName }}&lt;/li&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  name: &quot;Computed&quot;,
  data() {
    return {
      superHeros: &#x5B;],
    };
  },
  async mounted() {
    try {
      response = await fetch(&quot;https://akabab.github.io/superhero-api/api/all.json&quot;);
      if (response.ok) {
        this.superHeros = await response.json();
      }
    } catch (error) {
      console.log(error);
    }
  },
  computed: {
    formattedSuperHeroNames() {
      let formattedNames = &#x5B;];
      this.superHeros.forEach((superHero, index) =&gt; {
        const name = superHero.toUpperCase();
        formattedNames.push({ heroName: name, id: index });
      });

      return formattedNames;
    },
  },
};
&lt;/script&gt;
</pre></div>


<p>Notice how within the template of the Vue component that formattedSuperHeroNames is being referenced, however it isn&#8217;t defined within the data property as we&#8217;d normally expect. Instead it is actually a function &#8211; which also shares the same name &#8211; that is defined within the computed object. <strong>We can treat any method that is defined within the computed property as if it was a normal property defined within the data property!</strong> </p>



<p>The above example simply hits an API once the component is mounted and then once the results are retrieved Vue knows to run formattedSuperHeros() which will iterate over the API response and make each super hero name all upper case letters. Imagine if you had an API where it returned a list of employees and each employee had their first name and last name split between two fields and you wanted to combine them &#8211; a computed property would be a great way at achieving this.</p>



<p>What about a watcher? A watcher is different than a computed property in the sense that a watcher <em>wacthes</em> another property and then when it changes it will perform some kind of side effect. A really simple example would be: <em>Keep track of the number of clicks. Once the number of clicks reaches 5 THEN make an API call.</em></p>



<p>Let&#8217;s see how this would work:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
&lt;!-- WATCHER EXAMPLE --&gt;

&lt;template&gt;
  &lt;div&gt;
    &lt;button @click=&quot;incrementClickCount&quot;&gt;Click me!&lt;/button&gt;&lt;br /&gt;
    Number of clicks: {{ numberOfClicks }}
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  name: &quot;Watcher&quot;,
  data() {
    return {
      numberOfClicks: 0,
    };
  },
  methods: {
    incrementClickCount() {
      this.numberOfClicks++;
    },
  },
  watch: {
    numberOfClicks(newValue, oldValue) {
      if (newValue === 5) {
        //HIT AN API END POINT!
      }
    },
  },
};
&lt;/script&gt;

</pre></div>


<p>One important thing to note is that a watcher MUST have the same name of the property that it is watching over. If it does not share the same name, it will never be invoked and instead just sit idle in your code. Vue also gives us access to both the newValue and oldValue of the property that we are watching, which allows us to more easily implement conditional logic as shown in this example. We&#8217;re waiting for the user to click the button exactly 5 times, and then once that happens we hit an API. A good example of this would be for some kind of error logging functionality where we want to see if the user is experiencing some kind of UI issue and is repeatedly clicking/tapping a button over and over again.</p>



<h2 class="wp-block-heading">tl;dr version</h2>



<p>A computed property is best suited for formatting/interacting with a pre-existing data property or prop that has been passed into the component via a parent component, but side effects aren&#8217;t desired (Nor should they be introduced via a computed property). A watcher is best suited for when a side effect should happen in response to a certain property/prop changing or reaching a certain value.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Converting JS Promise chain to async/await</title>
		<link>https://www.chrisphilbin.net/converting-js-promise-chain-to-async-await/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 26 Jan 2023 12:40:34 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=339</guid>

					<description><![CDATA[One of the more nuanced areas of JavaScript is the concept of Promises, which are exactly what they claim to be: A Promise to represent a value sometime in the&#8230;]]></description>
										<content:encoded><![CDATA[
<p>One of the more nuanced areas of JavaScript is the concept of Promises, which are exactly what they claim to be: <em><strong>A Promise to represent a value sometime in the future</strong></em>.</p>



<p>JavaScript code does not wait for a task to finish as it works through its thread of execution. As a result, we can say that JavaScript is a <em>synchronous language</em> &#8211; it never goes back up when executing code.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" src="https://chrisphilbin.net/wp-content/uploads/2023/07/turbo_man_promises.png" alt="" class="wp-image-423" width="565" height="310"/><figcaption class="wp-element-caption"><em>As Turbo Man always says: &#8220;Always keep your promises if you want to keep your friends&#8221;</em></figcaption></figure></div>


<h2 class="wp-block-heading"><strong>A quick refresher on Promises</strong></h2>



<p>A few months back I wrote <a href="https://chrisphilbin.net/demystifying-javascript-promises/">this post</a> about Promises and went into detail about what&#8217;s happening behind the scenes when a Promise is first created. Essentially, when created, a promise will immediately return a plain JavaScript object with a few blank/empty properties. Those properties being <em>value, onFulfillment[], onRejection[]</em>. </p>



<p>v<strong>alue</strong> is immediately undefined.</p>



<p><strong>onFulfillment</strong> is an empty array &#8211; we use the .then() method to push any functions we want to execute when the asynchronous task has completed successfully.</p>



<p><strong>onRejection</strong> is an empty array &#8211; We use the .catch() method to push any functions we want to execute when the asynchronous task has failed and caused an error.</p>



<p>Thanks to JavaScripts microtask queue in conjunction with the call stack, the functions that are pushed to either onFulfillment or onRejection will not run until the call stack is empty.</p>



<h2 class="wp-block-heading"><strong>A Traditional Promise Chain Example</strong></h2>



<p>Let&#8217;s take a look at a traditional Promise chain in which we will use node-fetch to hit an API and simply return its result to the console:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import fetch from &quot;node-fetch&quot;;

fetch(&quot;https://cdn.jsdelivr.net/gh/akabab/superhero-api@0.3.0/api/id/1.json&quot;)
  .then((response) =&gt; {
    return response.json();
  })
  .then((data) =&gt; {
    console.log(data);
  })
  .catch((error) =&gt; {
      console.log(error)
  })
</pre></div>


<p>It&#8217;s somewhat verbose, isn&#8217;t it? But taking into account what was discussed above about what each .then() call is doing, and what each .catch() call is doing, along with the interaction between the microtask queue and the call stack, it&#8217;s really not too difficult to unpack what&#8217;s going on.</p>



<p>We invoke fetch() with the API URL as its argument, we then define two arrow functions to push into the microtask queue: The first function (The argument of the first .then() call) parses the response as JSON, the second function (the argument for the second .then() call) receives that parsed JSON and outputs it to the console. Finally, in the event of an error, we created a function that will simply take the error and display it to the console (This function is the argument given to the .catch() method).</p>



<p>Not bad &#8211; Roughly 12 lines of code, but there is an even easier way: Enter <strong>async/await</strong></p>



<h2 class="wp-block-heading">Async/Await</h2>



<p>In 2017 (ES8) async/await was introduced into the language spec and one of the main goals behind this feature is to make writing, maintaining, and understanding asynchronous code a little easier. Let&#8217;s replicate the above example &#8211; we&#8217;ll hit an API, parse the response, and finally display it to the console.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const heroResponse = await fetch(&quot;https://cdn.jsdelivr.net/gh/akabab/superhero-api@0.3.0/api/id/1.json&quot;);
const heroData = await heroResponse.json();
console.log(heroData);
</pre></div>


<p>Thanks to async/await, In just three lines of code we did what used to take us about a dozen. The <strong><em>await</em></strong> keyword is taking what would have previously been assigned to the promise&#8217;s undefined value and instead assigns it to whatever is to the left of the equals sign (assignment) &#8211; It&#8217;s simply a further abstraction to the traditional .then() promise chain.</p>



<p><strong>What about error handling?</strong></p>



<p>This is a good question. Usually when implementing the new async/await API, you&#8217;ll also want to pair it with a try/catch block. A try/catch block literally means &#8220;First, try running this code. If for some reason you encounter an error, catch it, and then run this code with whatever error you caught as an argument&#8221;.</p>



<p>Let&#8217;s add it to the above example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
  try{ 
    const heroResponse = await fetch(&quot;https://cdn.jsdelivr.net/gh/akabab/superhero-api@0.3.0/api/id/1.json&quot;);
    const heroData = await heroResponse.json();
    console.log(heroData);
  } catch (error) { 
      console.log(error)l
  }
</pre></div>


<p><strong>What about the keyword &#8216;async&#8217;?</strong></p>



<p>Another good question. In the above two async/await examples the async keyword was not even used once. So why is it called async/await then? If the code we&#8217;re writing is in the global execution context, then it is implicitly async code and we can use <strong>await</strong> without it.</p>



<p>However, if we were to take the above code and create a new function so we can use it over and over again, then we would have to use the <strong>async</strong> keyword. Here&#8217;s how we would bring it all together:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
const getHeroInfo = async () =&gt; {
  try {
    const heroResponse = await fetch(&quot;https://cdn.jsdelivr.net/gh/akabab/superhero-api@0.3.0/api/id/1.json&quot;);
    const heroData = await heroResponse.json();
    console.log(heroData);
  } catch (error) {
    console.log(error);
  }
};
</pre></div>


<p>Notice at the top of the arrow function&#8217;s definition (Literally in between the equals signs and the set of open/close parenthesis where we&#8217;d define our parameters) the keyword <strong>async<em> </em></strong>is being used. This tells JavaScript that the code within this function is asynchronous and to treat it accordingly. </p>



<p>Even in 2023, about 5 years after async/await was introduced to the language, you will still see a mix of both .then() chaining and async/await syntax in existing code bases. For the most part, it boils down to personal preference, as well as what the rest of your team is doing/comfortable with.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Demystifying Javascript Promises</title>
		<link>https://www.chrisphilbin.net/demystifying-javascript-promises/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 09 Aug 2022 22:53:40 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=278</guid>

					<description><![CDATA[Javascript promises can be one of the more obscure concepts to understand for beginner developers as well as some mid-level developers. According to the official Javascript language spec, a promise&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Javascript promises can be one of the more obscure concepts to understand for beginner developers as well as some mid-level developers.</p>


<div class="wp-block-image is-style-default">
<figure class="aligncenter size-full is-resized"><img decoding="async" src="https://chrisphilbin.net/wp-content/uploads/2023/07/promise.jpg" alt="" class="wp-image-420" width="585" height="329"/></figure></div>


<p>According to the official Javascript language spec, a promise is:</p>



<p>“<em>&#8230;a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action&#8217;s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a </em><em>promise</em><em> </em><em>to supply the value at some point in the future.”</em></p>



<p>Still confused? Put a different way – A javascript promise is a plain old javascript object that represents a future value so the rest of the code can still be carried out in a synchronous manner. Javascript is non-blocking – this means that it will not wait for a task to complete before moving on to the next line. Instead of waiting for the asynchronus task to complete, the promise object acts as a “place holder” to represent the future value.</p>



<p>The promise object contains several crucial key/value pairs:</p>



<p><strong>Value</strong> – Immediately is undefined and upon successful fulfillment of the operation, value will contain the resulting data that has been returned.</p>



<p><strong>OnFulfillment</strong> &#8211; Initially, an empty array that will serve as a “repository” of methods to invoke if and when the promise has resolved successfully.</p>



<p><strong>OnRejection</strong> – Initially, an empty array that will again serve as a “repository” of methods to invoke if and when the promise has not resolved successfully.</p>



<p>So in summary, the promise object will immediately look like this:</p>



<p><code>{ value: undefined, onFulfillment: [], onRejection: [] }</code></p>



<h2 class="wp-block-heading"><strong>Where does .then() and .catch() come into play?</strong></h2>



<p>One common misconception is that .then() and .catch() are some kind of magical methods that will allow the code within the parenthesis to somehow to run sometime in the future. Though technically true in that they do allow code to be run in the future, the way both methods work under the hood are somewhat simplistic in nature so it <em>seems</em> like magic to us.</p>



<p>.then() and .catch() are essentially <em>pushing</em> the function that we define within the parenthesis into the respective empty arrays on the newly created promise object this way they can be invoked once the time comes. (More on this in a bit)</p>



<p>So if we write <strong>myPromise.then(response =&gt; console.log(response))</strong></p>



<p>We are more or less doing the following:</p>



<p><code>const futureFunction = (response) =&gt; console.log(response)<br>myPromise.onFulfillment.push(futureFunction)</code></p>



<p>And if we write <strong>myPromise.catch(response =&gt; console.log(response))</strong></p>



<p>We are more or less doing the following:</p>



<p><code>const futureFunction = (response) =&gt; console.log(response)<br>myPromise.onRejection.push(futureFunction)</code></p>



<p>Once the promise has resolved the value is the inherently passed in to each provided function – in the above example we’re calling the value “response”. A lot of times in production code when making a fetch request to an API you will see a conditional checking if response.ok – this means that we’re checking to see if the HTTP status code we received back from the server is 200 (technically 2xx).</p>



<h2 class="wp-block-heading"><strong>When do the functions we provide to .then() and .catch() actually run?</strong></h2>



<p>This can probably be its own blog post on its own given how in depth you can get with this topic. The functions we provide to .then() and .catch() don’t just run whenever we finally get a response back from whatever task we initially started. Remember: Javascript is non-blocking so once it’s done with a line of code that’s it – it’s not going to suddenly go back up several lines in the execution context and re-run lines of code because we got a response back from an API call.</p>



<p>Enter the concept of the call stack, the event loop, and the microtask queue.</p>



<p>While we are executing our Javascript code we’re constantly pushing and popping things from the call stack – We will start in the global execution context and then as we enter functions we find ourselves diving deeper and deeper into the execution contexts of those same functions and therefore pushing more and more onto the call stack. Remember: The call stack is like a stack of dishes in your sink – When you go to wash the dishes you’re going to take the dish that is at the top of the stack first and start washing it. This is know as Last In First Out, or LIFO for short. As we finish running those functions we pop them off of the call stack… And finally, when we’re done running all of the code in the Javascript file (the global execution context) we pop global off of the call stack as well and it’s finally empty – and then the magic can start.</p>



<p>The event loop essentially keeps checking to see if the call stack is empty. Once the call stack is indeed empty it will then allow any finished asynchronous tasks that have finished to then run – When a promise is finally resolved or rejected the contents of either the onFullfillment or onRejection arrays are then moved from the microtask queue onto the call stack via the event loop to finally be executed.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
