[Valid RSS] This is a valid RSS feed.


This feed is valid, but interoperability with the widest range of feed readers could be improved by implementing the following recommendations.


  1. <?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="" xmlns:content="" xmlns:atom="" version="2.0" xmlns:cc="">
  2.    <channel>
  3.        <title><![CDATA[Stories by Colton Kaiser on Medium]]></title>
  4.        <description><![CDATA[Stories by Colton Kaiser on Medium]]></description>
  5.        <link></link>
  6.        <image>
  7.            <url>*j_XN068kOmokz65-GiTbLg.jpeg</url>
  8.            <title>Stories by Colton Kaiser on Medium</title>
  9.            <link></link>
  10.        </image>
  11.        <generator>Medium</generator>
  12.        <lastBuildDate>Wed, 24 Apr 2024 11:54:33 GMT</lastBuildDate>
  13.        <atom:link href="" rel="self" type="application/rss+xml"/>
  14.        <webMaster><![CDATA[]]></webMaster>
  15.        <atom:link href="" rel="hub"/>
  16.        <item>
  17.            <title><![CDATA[How To Create A Unique Workout Planner With ReactJS]]></title>
  18.            <link></link>
  19.            <guid isPermaLink="false"></guid>
  20.            <category><![CDATA[software-development]]></category>
  21.            <category><![CDATA[javascript]]></category>
  22.            <category><![CDATA[react]]></category>
  23.            <category><![CDATA[programming]]></category>
  24.            <category><![CDATA[coding]]></category>
  25.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  26.            <pubDate>Mon, 09 Nov 2020 02:59:18 GMT</pubDate>
  27.            <atom:updated>2020-11-09T03:29:56.831Z</atom:updated>
  28.            <content:encoded><![CDATA[<figure><img alt="" src="*eAewxfmlF63vLFIJBaL3eA.png" /></figure><p>Recently, a leading athletic performance technology company told me they have a bit of a market gap in terms of keeping up with the competition. Currently, they offer a very effective way to track the performance of athletes, but they don’t have anything that tells coaches and athletes how to plan their workouts based on this information.</p><p>More and more companies are starting to emerge that create workout programs for teams, so they decided it’s time to implement something like this into their business model.</p><p>Coming from a heavy background as a strength and conditioning coach before I was a software engineer, I decided I was in a unique position to take this information and create something that could lead them in the right direction.</p><p>In this article, I’ll go over the step by step process of how I created this application.</p><h4>A quick side note that you probably don’t care about and can skip</h4><p><strong>Velocity Based Training (VBT)</strong>, is a means of strength training for athletes. More and more research/practical experience amongst strength and conditioning coaches is showing that weight training programs based on 1 Rep Max (1RM) are not very effective and can actually be counterintuitive. There are many reasons for this thought process but here’s a main few:</p><ul><li>Individual strength fluctuates day-to-day. An athlete’s 1RM one day could be drastically different the next. There are many factors for this but the main point here is that this makes 1RM an unreliable means to base programs off of. VBT takes this into account as main exercises are based on velocity on the day-to-day.</li><li>It doesn’t matter how strong an athlete is if they aren’t fast. VBT allows strength and conditioning coaches to base their weight training programs off of speed, rather than an arbitrary amount of weight. Not only this, but it allows them to have an actual metric of speed rather than just telling their athletes to “move the bar fast”.</li><li>Most VBT softwares show the athlete their speed in real-time. This results in increased motivation, competition, and fun during workouts.</li></ul><p><strong>This all being said</strong>, I want to be very clear. This article <strong><em>does NOT</em> require any sort of knowledge of fitness, sports, strength training, etc. </strong>It<strong> <em>does</em> </strong>require basic/intermediate knowledge of ReactJS, some knowledge of React Hooks, JavaScript syntax, and basic CSS.</p><h4><strong>Now, back to our regularly scheduled programming (no pun intended)</strong></h4><p>This application is a Single Page ReactJS application that utilizes <a href="">Material-UI</a> and a bit of custom CSS.</p><p><strong>Here’s what it will look like:</strong></p><figure><img alt="" src="*v9jDWyBcR5YwOIr7sY-VGg.gif" /></figure><p>If you’re wondering where the speed data is coming from, here’s the chart our VBT metrics in this application will be based on. Again, if you don’t understand this, don’t worry as it’s not expected or important. <strong>This is only for you to see what the data is based on.</strong></p><figure><img alt="" src="*sahNxyQE177kDojoSG_cyg.jpeg" /><figcaption>Source:</figcaption></figure><p>Let’s first briefly create our user stories.</p><h3>User Stories</h3><p><strong>User will be able to:</strong></p><ul><li>Select a workout day from a dropdown menu</li><li>Select their velocity from last month</li><li>Have the information be populated in a table based on this information</li></ul><p>We’re going to be using the React UI framework, Material-UI, to create our dropdown menus and table.</p><p>We install this by entering npm i @material-ui/core into the terminal.</p><h3>The Data</h3><p>For this to be a hosted SPA (Single Page Application) that didn’t require a backend, I created a small data file with information that will be pulled into the table cells. We export these three arrays of objects in one Data object at the bottom of the file.</p><figure><img alt="" src="*iCwjkntLP8oiLsTFsrcbBA.png" /></figure><p>Yes, this information is hardcoded and would not be like this in a full-fledged commercial application (as opposed to pulling from an API, user input, etc.). For now, this data is used specifically to keep our application simple.</p><h3>App level component</h3><p>Since we’re using hooks for this app, we’ll need to import useState from React. We&#39;re also going to be creating the day dropdown menu from this level, so we&#39;ll need to import the TextField and MenuItem components from Material-UI. Form is a folder created to house our velocity dropdown menu.</p><figure><img alt="" src="*XJludiwMpqtsPb0qgC0Zag.png" /></figure><p>Next, since we’re going to need to tell our app which day it should use to populate the exercises on the table. We’ll handle that as state on the App level.</p><figure><img alt="" src="*f0bw7oTTWI39ooAIyyUxkw.png" /></figure><p>We’ll pass this information down to our Form component as props.</p><figure><img alt="" src="*iKEwdWDDqEBzHJvwCNxvQA.png" /></figure><p>Next, let’s create a changeDay() function that sets our state based on the value of what was clicked in the dropdown (either &quot;Upper Body&quot; or &quot;Lower Body&quot;).</p><figure><img alt="" src="*7EOBSo2jI8QdQXM9sHkP4Q.png" /></figure><p>Lastly, we need to create our Day dropdown menu using Material-UI. Then have our changeDay() function each time an option is clicked. Thus setting the day state to whichever option is selected (remember this is being passed down to our Form component, which we will get to next).</p><figure><img alt="" src="*EkfbWdk4NHmeHzccbSDPTg.png" /></figure><p>Here’s what we get:</p><figure><img alt="" src="*OSAv5z5HSBPkZkrWhmL0Sg.gif" /></figure><p>Here’s what our file looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h3>Velocity dropdown form component</h3><p>Let’s do our imports first. We’ll need useState and useEffect from React, our workout/velocity data from our Data file, a WorkoutTable component that we will render here and pass down props to, and the TextField and MenuItem components from Material-UI.</p><figure><img alt="" src="*6qCH-sF_AkTx6vZMwW4wsA.png" /></figure><p>We’ll need the day prop that we passed down from the app level, and we&#39;ll also need to have our velocity range string (for the table) and velocity name string (for the title of the phase) as state. We&#39;ll then pass these down to the table component.</p><figure><img alt="" src="*NHqXTmmQMDV9OhgNFOymuA.png" /></figure><figure><img alt="" src="*NwnHpXzIJfl0DpzWCyWsZg.png" /></figure><p>Let’s create a function similar to the one on the App level that takes the selection from the menu and sets it as state.</p><figure><img alt="" src="*PrxYDFW7JIqZS3QWl62esg.png" /></figure><p>Now we’ll create our dropdown. Similar to the app level, we’ll need to call our changeVelocity() function any time a new option is clicked. We&#39;ll also need to set the velocity ranges as choices in the dropdown menu.</p><figure><img alt="" src="*R_4Lomnv0qZzocsIxhLS5w.png" /></figure><p>Here’s what we’re left with:</p><figure><img alt="" src="*LIE7CuTBslb0jxKe2gXpCg.gif" /></figure><p>We’re still left with another task. We need to handle retrieving the name of the velocity phase from the object relative to what was selected from the dropdown menu so we can make that the title of the chart when it’s populated.</p><p>We’ll handle this by creating a function called getVelocityName() that filters through the Velocities array from our Data file and finds/returns the object that has the same range value as the one that has been selected in the dropdown menu. Then set this to be our velocityName state so we can pass it down as props to the table component.</p><figure><img alt="" src="*w4fiSsdEseySc_zdtCqDyw.png" /></figure><p>But there’s a problem. We need this to happen each time another option is clicked, not just on initial render. We’ll use useEffect for this and set its dependency array to the velocityRange state. This way, any time the velocityRange state is updated due to an option being selected, so will velocityName.</p><figure><img alt="" src="*ZUqEI9b0W0CsZEnUEN9nlA.png" /></figure><p>So here’s what our file looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h3>Workout Table Component</h3><p>First, we need to import useState and useEffect, our Data object, and all of the Material-UI table components. We will also import a few more things from Material-UI: Paper to give our table an elevated effect, Container to surround the table, and Typography since we&#39;re feeling a little fancy today (it&#39;s to change the font of our titles.).</p><figure><img alt="" src="*YjNaC16ILPT8JfgToqGX8A.png" /></figure><p>For the purposes of this app, our main lifts will only consist of two options: &quot;Bench Press&quot; and &quot;Squat&quot;. These will flip flop based on whether &quot;Upper Body&quot; or &quot;Lower Body&quot; as been selected from the menu on app level. We will set this in state as MainLift. We&#39;ll also need the rest of our exercises and sets/reps to fill out the remainder of the chart, so we&#39;ll store that in state as well.</p><figure><img alt="" src="*BFb5LnHPIBPgoPy0Saz92A.png" /></figure><p>Notice how we’re also grabbing our props from the upper levels.</p><p>Let’s set up our functions that will change both of our state objects to their respective days.</p><figure><img alt="" src="*0euRf9m1vsJpRlTD9-mpSA.png" /></figure><p>Okay, so now we want to call one of these functions based on whichever day prop has been sent down each time a selection is made on that form. We will again use useEffect for this and set it&#39;s dependency array to consist of the day prop we&#39;re being passed. This way, any time day changes, the respective function will be called.</p><figure><img alt="" src="*d8YZ14NWYu_dY00MXPTZyw.png" /></figure><p>Now we need to set up a plan for how we will populate the “Target Velocity” column in the table, as well as how we will populate it’s respective name above the table (“Speed-Strength”, etc.).</p><p>This is a bit more complicated than it sounds. Not only do we need to grab the correct velocity object, but since the object being used needs to be <strong><em>one ahead</em> </strong>of whatever has been selected in the dropdown menu (remember it’s populating their<strong> <em>next</em> </strong>phase), we’ll need to handle this all accordingly.</p><p>Let’s start by creating a function that grabs the current velocity object based on whichever velocityName prop was sent down and uses this to find what index it is located in in our Velocities array. This way, we can use that information to grab the next one ahead of it.</p><figure><img alt="" src="*_JP9U67CRs023zrryccwJQ.png" /></figure><p>Now we’ll create two more functions to get the name (to populate the title) and range (to populate the velocity table cell) of whichever velocity object is one step ahead of the index we returned above. We also need to make sure that if the last object in the array is selected, we display the object at index 0. Otherwise, we’d be grabbing undefined.</p><figure><img alt="" src="*2ZRlVl1lvmnQmtH6IoN6zQ.png" /></figure><p>Finally, we will create our table. We are going to need a conditional here. We only want the table to display once both dropdown menus have been selected. Until they’ve <strong>both</strong> been selected, we’ll display instructions.</p><p>Once the table is displaying, we’ll need to use our current exercises array which is set in state each time the day prop is changed to populate the exercises and sets/reps. Above that, we&#39;ll populate the main lift based on the day, and the velocity range based on our function above.</p><p>Here’s what this ends up looking like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p><strong>The final product:</strong></p><figure><img alt="" src="*v9jDWyBcR5YwOIr7sY-VGg.gif" /></figure><h3>Biggest Challenges</h3><p>The biggest challenge for this app was the large amount of conditionals, resulting in a challenging way to write the code that was readable and understandable to others.</p><p>This was dealt with by creating very clear and concise function and variable names as well as descriptive comments for anything that may be confusing to read for an outsider. Functional programming was also used to combine any complicated statements/expressions into understandable chunks.</p><h3>Future Goals</h3><p>As mentioned at the beginning of this article, this app could have a lot more features added to it. These include:</p><ul><li>Allowing the user to add their own exercises</li><li>A login/logout function that saves the user’s progress</li><li>Ability to record weights</li><li>More options for the types of days</li><li>Automatic integration from VBT software</li><li>Multi-day view</li><li>Display based on the type of program the athlete is on (amount of days/week, etc.)</li><li>and lots more…</li></ul><p>Is there anything you would’ve done differently? Let me know in the comments!</p><p>PS: Here’s a link to the GitHub repo: <a href=""></a></p><img src="" width="1" height="1" alt=""><hr><p><a href="">How To Create A Unique Workout Planner With ReactJS</a> was originally published in <a href="">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  29.        </item>
  30.        <item>
  31.            <title><![CDATA[JavaScript Under The Hood Pt. 7: IIFEs]]></title>
  32.            <link></link>
  33.            <guid isPermaLink="false"></guid>
  34.            <category><![CDATA[javascript]]></category>
  35.            <category><![CDATA[programming]]></category>
  36.            <category><![CDATA[coding]]></category>
  37.            <category><![CDATA[software-development]]></category>
  38.            <category><![CDATA[software-engineering]]></category>
  39.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  40.            <pubDate>Mon, 02 Nov 2020 01:58:08 GMT</pubDate>
  41.            <atom:updated>2020-11-04T13:54:32.850Z</atom:updated>
  42.            <content:encoded><![CDATA[<figure><img alt="" src="*p3tRoH5_rSnYczRFPzitZg.png" /></figure><p><strong>Welcome back to the Bite-Sized Advanced Javascript series,</strong> where we discuss advanced JavaScript concepts in an easy-to-understand and concise fashion.</p><p>The first time you heard the statement Immediately Invoked Function Expression (IIFE), you might have been a little intimidated. But, like many JavaScript concepts, it’s fairly straightforward and not as scary as it sounds.</p><p>Before we get into the weeds of what IIFEs are and what they’re used for, it’s important to go over a little vocabulary.</p><p>Understanding the concept of <strong>function statements</strong> vs. <strong>function expressions</strong> is critical to fully understand and appreciate the concept of IIFEs.</p><p>Let’s jump right in.</p><h3>Function Statements</h3><p>Put simply, a function statement will start with the word function when it&#39;s defined. Example:</p><pre>//Function statement</pre><pre>function greet(name) {<br>   console.log(‘Hello ‘ + name)<br>}</pre><pre>greet(“Colton”)<br>//Hello Colton</pre><p>Function statements are hoisted in memory their entirety, so they’re safe to use even before they’re defined in the lexical environment:</p><pre>greet()<br>//hi<br>​<br>function greet() {<br>  console.log(&quot;hi&quot;);<br>}</pre><p>(If you need a review on the concept of hoisting, see my article on the topic <a href="">here</a>)</p><h3>Function Expressions</h3><p>In contrast, a function expression is an anonymous function that is assigned to a variable.</p><pre>//Function expression<br>var greet = function(name) {<br>  console.log(&#39;Hello &#39; + name)<br>}<br>​<br>greet(&quot;Colton&quot;)<br>//Hello Colton</pre><p>Let’s elaborate on why this is significant.</p><p><strong>An expression is a unit of code that returns a value.</strong> Expressions don’t need to be saved to a variable in order to be used. Here’s an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>2 + 2 and a === 3 are examples of <strong>expressions</strong> because they immediately return a value. They don&#39;t need to be saved to a variable in order to be used. We can think of our if statement as an example of a <strong>statement</strong> (the hint is in the name). This is because the if statement <strong><em>itself</em> </strong>(not the code inside of it), doesn&#39;t return anything on its own.</p><blockquote><em>Expressions immediately return a value. They’re often used without being saved to a variable.</em></blockquote><p>So, knowing what we now know about expressions, let’s combine this with what we know about functions in JavaScript.</p><p>JavaScript is a special language. One of the main reasons it’s so special, as discussed in other articles in this series, is that everything is an object in JavaScript, <strong>including functions</strong>. This is quite unique and is what makes JavaScript such a flexible, easy-to-read, and concise language. (It’s also part of what makes it sometimes confusing and prone to bugs if not understood fully, but we won’t get into that here).</p><p>Since functions are objects, we can store them in variables, just like any other object. And since everything is an object in JavaScript, we can do weird things with functions if we want to. We can even pass functions as arguments into other functions! (Is your mind blown yet?):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now here’s a key point to mention about function expressions. Since function expressions are stored as variables, <strong>they aren’t hoisted like function statements are</strong>. Like regular variables, they are set equal to undefined until the variable is assigned. So you can run into trouble if you try something like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Understanding this concept is a key part of preventing hard-to-find bugs for yourself and your team.</p><blockquote><em>Function expressions aren’t hoisted. Only the variable is hoisted (to undefined).</em></blockquote><p>Armed with this knowledge and the fact that we know expressions return a value immediately without needing to be invoked, let’s get into Immediately Invoked Function Expressions (IIFEs).</p><h3>Immediately Invoked Function Expressions (IIFEs)</h3><p>Functions are objects, but they aren’t ordinary objects. They’re a special type of object in that they have a “code” property which can be invoked ().</p><p>Here’s the kicker: We can invoke a function at the point of creation. In other words, we can create a function object and immediately invoke it:</p><pre>//Using an Immediately Invoked Function Expression (IIFE)</pre><pre>var greeting = function(name) {<br>  return &#39;Hello &#39; + name<br>}()</pre><pre>//Can immediately invoke a function at the point of creation.<br>//Creates a function object and immediately invokes it.</pre><pre>console.log(greeting)</pre><pre>//Works like greeting()<br>//Logs &quot;Hello undefined&quot;</pre><p>We’ve just defined a function expression that doesn’t need to be invoked when it’s called, since it’s already being invoked upon creation. Writing greeting() would now cause an error.</p><p>We can pass parameters into IIFEs as well, just like with a normal function call!</p><pre>var greeting = function(name) {<br>  return &#39;Hello &#39; + name<br>}(&#39;Colton&#39;)</pre><pre>console.log(greeting)</pre><pre>//Works like greeting(&#39;Colton&#39;)<br>//Logs &quot;Hello Colton&quot;</pre><p>Writing greeting(&quot;Colton&quot;) here would, again, cause an error.</p><p>Seems pretty simple so far right? Well, here’s where things can get a little hairy.</p><p>In JavaScript, we can write lines of code that aren’t defined without receiving any errors.</p><pre>3;</pre><pre>&quot;I&#39;m a string&quot;;</pre><pre>{ name: &#39;Colton&#39; };</pre><pre>//This is all valid Javascript and doesn&#39;t cause an error upon running even though none were assigned a variable.</pre><p>Let’s try to do this with a function expression:</p><pre>function(name) {<br>  return &#39;Hello &#39; + name<br>}</pre><pre>//Uncaught SyntaxError: Function statements require a function name</pre><figure><img alt="" src="*4Gc0OXuJGKYMzxczFSop_Q.png" /></figure><p>What happened here?</p><p>The syntax parser saw the word function in a new line of code without a variable before it, so it expected a function <strong>statement</strong>. When it didn&#39;t see a name for the function, it threw an error asking for one.</p><p>We need to find a way to “trick” the syntax parser. In other words, we need to make it so function isn&#39;t the first thing it sees. As long as this isn&#39;t the first thing it sees, it will no longer assume we&#39;re trying to create a function statement since function expressions have <strong>something</strong> in front of the word function.</p><p>There are a few ways to do this, but the most common/accepted way is to <strong>wrap the function in parentheses</strong>.</p><pre>(function(name) {<br>  return &quot;Hello &quot; + name)<br>})</pre><pre>//No errors!</pre><p>This is the most accepted method since it’s the easiest to read and understand. Now, we can call a function expression without needing to assign it a name.</p><p>Parentheses in JavaScript is an operator, and operators are only used with <strong>expressions</strong>. So the JavaScript engine can safely assume that whatever is inside the parentheses must be an expression.</p><blockquote><em>Function expressions that aren’t assigned a variable name need to be wrapped in parentheses.</em></blockquote><p>Let’s use this knowledge to create an IIFE:</p><pre>//IIFE</pre><pre>(function(name) {</pre><pre>  console.log(&quot;Hello &quot; + name)</pre><pre>}(&#39;Colton&#39;))</pre><pre>//Hello Colton</pre><p>Now, we’ve created and ran a function, all at the same time.</p><p><strong>This is most often what we’re talking about when we talk about IIFEs.</strong></p><h3>When/why are IIFEs used?</h3><p>A knowledge of IIFEs can be a powerful tool for you as a software developer. They are used in almost every major framework or library out there, and being able to crack into and understand these are huge.</p><p>Not only this, but <strong>they can make your code safer.</strong></p><p>We know that a function holds its own execution context, and <strong>variables declared inside of it are specific to that execution context</strong> (For a review on the global environment and execution contexts, view my article on the topic <a href="">here</a>). The variables cannot be accessed elsewhere.</p><p><strong>Variables declared inside a function don’t touch the global environment.</strong> This is the heart of what makes IIFEs so commonly used in frameworks and elsewhere.</p><p>For example, let’s say we have an index.html file that calls on multiple script files. What happens if these script files both have a variable with the same name, but different values in the global environment? There would be a collision and one of the variables would not return what we expect it to (it would return the return value of whatever file takes precedence instead). Talk about a recipe for hard-to-catch bugs!</p><p>Frameworks and libraries will often wrap their entire code-base in an IIFE for this reason. Since all their variables are wrapped in a function, there’s no risk of collision in other files in your application since all of the variables declared in that file exist only in their own execution context.</p><p>This can help immensely in your own code as well as it allows for more reusability.</p><p><strong>In summary:</strong></p><ul><li><strong>Function statements</strong> start with the word function and aren&#39;t explicitly assigned a variable. They are hoisted in memory in their entirety so can be used earlier in the lexical environment.</li><li><strong>Function expressions</strong> are anonymous functions that are called on the fly. They can be assigned to a variable or used to create an IIFE.</li><li>Function expressions can be called immediately upon creation. This is what an IIFE is.</li><li>IIFEs can be assigned a variable but are often kept as function expressions that are called immediately upon creation. They can even be assigned arguments and passed parameters.</li><li>Parentheses need to surround an IIFE since the syntax parser needs to see something before the word function so it can tell a function statement is not trying to be created.</li></ul><p>How has understanding function statements, function expressions, and IIFEs impacted your programming? Feel free to share in the comments!</p><p>For more bite-sized advanced JavaScript concepts, check out the rest of the series!</p><img src="" width="1" height="1" alt=""><hr><p><a href="">JavaScript Under The Hood Pt. 7: IIFEs</a> was originally published in <a href="">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  43.        </item>
  44.        <item>
  45.            <title><![CDATA[JWT Tokens: The What, How, and Why]]></title>
  46.            <link></link>
  47.            <guid isPermaLink="false"></guid>
  48.            <category><![CDATA[programming]]></category>
  49.            <category><![CDATA[security]]></category>
  50.            <category><![CDATA[software-engineering]]></category>
  51.            <category><![CDATA[javascript]]></category>
  52.            <category><![CDATA[software-development]]></category>
  53.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  54.            <pubDate>Mon, 26 Oct 2020 00:57:16 GMT</pubDate>
  55.            <atom:updated>2020-10-29T19:25:08.607Z</atom:updated>
  56.            <content:encoded><![CDATA[<h4>Learn how JavaScript Web Tokens can make your app more secure and how they work</h4><figure><img alt="JSON Web Token logo" src="*AMeiWwTqbLAUe0bvdVTVLA.png" /><figcaption>Credit:, <a href=""></a></figcaption></figure><p>When I first learned about the processes of encryption, authorization, authentication, cookies, JWT tokens, etc., I was pretty overwhelmed. Getting into the weeds of these topics is extremely complex and can be confusing, which is why cybersecurity is an entire field in itself. But gaining, at the very least, a surface level understanding of these topics is important as a developer.</p><p>In this article, we’ll gain an understanding of something that is becoming a very popular method of authorization, <a href="">JSON Web Tokens</a> (JWT).</p><p>While the topics in this article don’t even scratch the surface of cybersecurity, they’re very important to understand and be aware of as a software developer.</p><p>Key point: Understanding the security process is an important part of being a developer.</p><h3>What’s the Difference Between Authentication and Authorization?</h3><p>To put it simply, authentication is the first step in any security process. This beginning process verifies credentials (an example being a password or the facial recognition on your phone) and confirms the user is who they say they are. Authorization (where JWT comes into play) gives the user access to specific functions or resources. An example could be authorizing that the user has access to financial records, if they can perform admin actions, etc.</p><p>A simple definition from <a href="">an article from</a>:</p><blockquote>“Authentication confirms that users are who they say they are. Authorization gives those users permission to access a resource.”</blockquote><p>In other words, authentication is the bouncer at the club checking your ID to make sure you’re 21 and allowed in the building; authorization is the stamp he gives you to allow access back into the club or confirming you’re allowed in the VIP area.</p><p>Key point: Authentication validates a user and authorization gives the user access to specific functions or resources.</p><h3>Enter Cookies</h3><p>To understand why JWT is useful and how it’s different, we need to have a brief understanding of another method of authorization: cookies.</p><p>Here’s an example of a session that uses cookies for authorization:</p><ol><li>A user logs in to a site (is authenticated) from their browser (known as <em>the client</em>).</li><li>The server saves their session in server memory and assigns a unique session ID that corresponds with that part in memory.</li><li>The server then sends this session ID back to the client as a cookie. This way, the browser always has access to the session ID and is able to send it to the server any time it makes a request.</li><li>Now a user tries to access a page. The browser then sends a request with the session ID cookie to the server.</li><li>The server receives this ID and checks to see if it exists in memory. Once the server sees the ID exists in memory, it checks to see if the user with that ID is authorized to access the page, function, etc., they’re trying to access.</li><li>The server then sends a response back to the client saying if they’re authorized for this action or not, and the browser acts accordingly.</li></ol><h3>Where Does JWT Come In?</h3><p>The beginning of a session that uses JWT for authorization starts similarly, but then there are some key differences.</p><p>Here’s an example of a session that uses JWT tokens for authorization rather than cookies:</p><ol><li>A user logs in to a site (is authenticated) from their browser (known as <em>the client</em>).</li><li>Now, instead of the server storing the user’s session in server memory, it creates a JSON Web Token, encodes it, serializes it, and signs it with a unique secret key. This secret key allows the server to know if the token has been tampered with.</li><li>The server then takes the JWT and sends it back to the browser. The main difference here: Nothing is stored on the server. The JWT has all the necessary information about the user built into it.</li><li>The browser then stores the JWT token (a common way is by using the browser’s local storage).</li><li>The user then tries to access a page, and the browser sends a request with the JWT (similar to what was done with the session ID cookie in the example above) to the server so it knows which user is requesting authorization.</li><li>The browser then checks the secret key it gave the JWT in the very beginning to make sure it wasn’t changed. This way, if the user changed the user in that JWT token, the server will know and say it’s invalid.</li><li>Once confirmed that the JWT is valid, the server then sends a response back to the client saying if they’re authorized to perform the requested action or not (similar to above).</li></ol><p>The main difference to notice here is that with cookies, the information is stored server-side, while with JWT, since the information is stored in the actual token, the information is stored client-side. Since the server doesn’t need to remember anything, this simplifies things a lot, especially when working with multiple servers and having different sessions.</p><p>Key point: A key difference between cookies and JWT tokens is that cookies are stored on the server, while JWT tokens are stored client-side.</p><h3>How Do JWT Tokens Work?</h3><p>Let’s take a trip to <a href=""></a> and break down what we see.</p><figure><img alt="" src="*1JgFnSiksdTS7y9pkozDtw.png" /></figure><p>On the left, we have the encoded version of the JWT, which is what is sent to and from the client.</p><p>On the right, we have the decoded version, which has three different parts:</p><ol><li>The Header, which determines the algorithm used to encode and decode the token (the different algorithms are outside the scope of this article and, honestly, very rarely necessary to change).</li><li>The Payload, which is all the information that is stored in the token.</li><li>The Signature, which is how the server verifies the token hasn’t been changed by the client before sending it back.</li></ol><p>You’ll notice that the JWT separates these three parts with periods, making them easy to identify.</p><h3>The Header</h3><figure><img alt="encoded JWT header" src="*KRNMUTcBr-OkFv8Src56EA.png" /><figcaption>Header encoded</figcaption></figure><figure><img alt="decoded JWT header" src="*oqyLE8pyjHchxm3tl0ti6g.png" /><figcaption>Header decoded</figcaption></figure><p>As mentioned above, discussing the different types of algorithms that can be used in the header is outside the scope of this article. The important thing to know here is that this is what is used to decide how the token is encoded and decoded.</p><h3>The Payload</h3><figure><img alt="encoded JWT payload" src="*AZXVhV7_CmoHF-2OtOYBaQ.png" /><figcaption>Payload encoded</figcaption></figure><figure><img alt="decoded JWT payload" src="*DTrQpKSUoAc8EH8Buvvvmw.png" /><figcaption>Payload decoded</figcaption></figure><p>The payload is where all the data on the user is stored and is the bulk of what your application is in charge of. Any key/value pairs can be put in this component, but there are some common fields you’ll see:</p><ul><li>The sub (or subject) is usually the ID of the user being authorized.</li><li>The name. This may come as a shock but the name is usually the name of the user.</li><li>iat, which stands for “issued at.” This says when the token was created. This can be useful if you want to expire tokens (often saved as exp or eat, which stands for “expired at”).</li></ul><h3>The Signature</h3><figure><img alt="encoded JWT signature" src="*gtKVg73bojAs7MQHei2IMQ.png" /><figcaption>Signature encoded</figcaption></figure><figure><img alt="decoded JWT signature" src="*GEW07AOH6Sq9xlFhTSwG0A.png" /><figcaption>Signature decoded</figcaption></figure><p>The signature verifies the user did not alter the token before it was sent back to the server.</p><p>This is the way it creates the signature:</p><ol><li>It takes the header and adds a period.</li><li>It takes the payload and combines it with the header (after the period).</li><li>It uses the algorithm defined in the header to encode the above-combined data using the secret key you define (the area where it allows you to type in the picture above).</li><li>This means that if the client alters even one character from the data, the signature won’t match anymore when it’s sent back to the server.</li></ol><h3>Why Use JWT?</h3><p>Let’s say a company owns two servers (apps, websites, etc.), for two different aspects of their business (or maybe it’s a huge business that can’t store all their users on one server, so it balances traffic between different servers). The company wants users who are logged in on one app/server to be automatically logged in to the other app/server should they switch over to it (this is often done seamlessly, without the user even noticing). They don’t want the user to have to log back in when switching over to the other server.</p><p>In a session-based server (cookie-based), since the session data is stored in the server’s memory and not in the browser, the user would need to log in separately on each server because the session is stored in one but not the other.</p><p>When using JWT, since the token is stored in the browser and not on the server, if you share the same secret key on both servers, then all you need to do is send the same JWT to each. This means the client can stay logged in, even when switching between servers.</p><p>Using JWT tokens allows the user to switch between servers without requiring a login each time they switch.</p><h3>Summary</h3><ul><li><strong>Authentication</strong> is what verifies the user is who they say they are.</li><li><strong>Authorization</strong> gives the user access to certain functions and resources. This is where JWT tokens come into play.</li><li><strong>Cookies</strong> are a method of authorization that uses a session ID stored on the server.</li><li>The most important reason <strong>JWT tokens</strong> are different from cookies is that they <strong>store the information client-side</strong>. The server doesn’t need to store anything.</li><li>JWT tokens have <strong>three different parts</strong>: the <strong>Header</strong>, which stores the algorithm used for encoding and decoding the token; the <strong>Payload</strong>, which stores all of the user information; and the <strong>Signature</strong>, which is how the server verifies the token hasn’t been altered.</li><li>Since JWT tokens are stored client-side, they are especially useful when you want to <strong>use multiple servers</strong> without the client needing to log in separately when switching between them.</li></ul><p>Have anything else to add about JSON Web Tokens, authentication, or authorization? Feel free to share in the comments!</p><img src="" width="1" height="1" alt=""><hr><p><a href="">JWT Tokens: The What, How, and Why</a> was originally published in <a href="">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  57.        </item>
  58.        <item>
  59.            <title><![CDATA[JavaScript Under The Hood Pt. 6: Asynchronous Callbacks]]></title>
  60.            <link></link>
  61.            <guid isPermaLink="false"></guid>
  62.            <category><![CDATA[coding]]></category>
  63.            <category><![CDATA[software-development]]></category>
  64.            <category><![CDATA[programming]]></category>
  65.            <category><![CDATA[javascript]]></category>
  66.            <category><![CDATA[software-engineering]]></category>
  67.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  68.            <pubDate>Mon, 19 Oct 2020 01:53:59 GMT</pubDate>
  69.            <atom:updated>2020-10-20T18:50:14.231Z</atom:updated>
  70.            <content:encoded><![CDATA[<h4>Understand asynchronicity vs. synchronicity in JavaScript, what these mean, and be able to explain them effectively to others.</h4><figure><img alt="" src="*2VVpfM7RoFsNOU0LFhcywQ.png" /></figure><p>Asynchronicity in JavaScript is a tricky topic to wrap your head around. Mainly because the word itself (or rather the way it’s used), in the concept of JavaScript, is misleading.</p><p>JavaScript is a single-threaded, synchronous language, meaning it reads one command (or line of code) at a time, in the order it appears. So how can it possibly be asynchronous? Well, here’s the thing to remember: <strong>JavaScript isn’t the only thing running when it’s being executed in your browser. </strong>This is the real nature of the concept of asynchronicity in JavaScript.</p><blockquote><em>JavaScript is a single threaded, synchronous language.</em></blockquote><h3>What do “single-threaded” and “synchronous” mean?</h3><p><strong>Single-threaded means one line at a time</strong>, and <strong>synchronous means in order (from top to bottom)</strong>. This is how the JavaScript engine executes its code. That’s it.</p><p><strong>This is true even when taking execution context into account.</strong> When the JavaScript engine is running code within a certain execution context, it might not be reading exactly from top to bottom within the global, <em>lexical</em> environment of the file as a whole, but it is still reading one line at a time (single-threaded) and in order from top to bottom (synchronous) within the respective execution context.</p><blockquote><em>Single threaded means one line at a time, and synchronous means in order (from top to bottom).</em></blockquote><h3>Then what about asynchronous callbacks?</h3><p>The definition of asynchronous is fairly simple. <strong>When we say asynchronous, we’re really just saying “more than one at a time”</strong>. But didn’t we just say JavaScript is synchronous? Yes, but remember, <strong>the JavaScript engine works in conjunction with other things in the browser when it’s running your code.</strong></p><p>Some examples:</p><ul><li><strong>The rendering engine: </strong>The engine that prints/paints to the screen.</li><li><strong>HTTP Request: </strong>The part of the browser that actually goes out and gets data.</li></ul><p>The JavaScript engine is able to “hook up” to these types of things during execution. So, while all of these may be running at the same time (or asynchronously), the JavaScript engine <em>itself</em> is running synchronously.</p><p>We know that in JavaScript we have something called the “execution stack”, where each execution context is completed, and then “popped off” the stack to go to the next one (If you’d like more information on the global environment and execution contexts, refer to my article <a href="">here</a>). Well, there’s also something running simultaneously along with your JavaScript code in the engine called the <strong>event queue.</strong></p><blockquote><em>Along with the execution stack, there’s also something called the event queue running in the JavaScript engine.</em></blockquote><p>The event queue is full of events that may be currently happening. <strong>When the browser receives an event that the JavaScript engine wants to be aware of</strong> (for example, a click), <strong>it is placed on the event queue</strong>. Whether the click is to be handled or not, it is still placed in the queue. Another example of this could be an HTTP request, where the browser is going out and getting data. This is also added to the event queue.</p><p><strong>The event queue gets looked at by JavaScript when the execution stack is empty.</strong> Once the entire execution stack is empty, the JavaScript engine waits and checks periodically if something has appeared in the event queue. <em>Then</em> deals with it accordingly if asked.</p><p>If there’s a function that is listening for that event (ex. a click listener). Then there is a new execution context created for the function that handles that event. After this, the next item in the event queue is looked at, and if a function calls on it, then it is added to another execution context.</p><p>Therefore, JavaScript is <strong>not</strong> running asynchronously. The browser is asynchronously putting things into the event queue, but the code that is running is still running line-by-line. One at a time.</p><h3>Show me the code.</h3><p>Let’s create a file that has a function which simulates a function that takes a long time and call it waitThreeSeconds(). This may come as a shock but this function does nothing for three seconds, then logs &quot;finished function&quot; in the console to let us know its execution context has ended.</p><p>We’ll create a clickHandler() event which lets us know when its execution has been run, and call this function on an event listener attached to the global environment.</p><p>After all is said and done, we’ll log “finished execution”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now, if we click <strong>during</strong> the waitThreeSeconds() execution (which is immediately upon page load), in what order do you think our console logs will show up?</p><figure><img alt="" src="*kGAAddxEtOHZMbZu7I5olg.png" /></figure><p>Can you guess why this happened? Why was the click event handled last, even though we clicked while another function was running? Because JavaScript is synchronous. <strong>The JavaScript engine won’t look at the event queue until the execution stack is empty</strong>. Once the stack was completely empty, <strong>then</strong> the JavaScript engine created an execution context for the clickHandler() function.</p><p>This is exactly why long-running functions can cause performance issues.</p><p>So, what have we learned?</p><ul><li><strong>JavaScript is a single-threaded, synchronous language.</strong> It executes its code line by line, in order from top to bottom (respective of execution contexts).</li><li><strong>JavaScript handles asynchronous events with something called the “event queue”.</strong> Once the execution stack is completely empty, it refers to the event queue, and if there are any functions that require handling one of the events, <strong><em>then</em> it creates execution contexts for them and handles them accordingly.</strong></li><li><strong>“Asynchronous” in JavaScript is more about what’s happening outside the JavaScript engine. (The browser, etc.)</strong></li></ul><p>How has understanding the nature of asynchronous callbacks in JavaScript informed your programming? Let me know in the comments. For more bite-sized advanced JavaScript knowledge, feel free to check out the rest of the series!</p><p>Enjoyed this article? If so, get more similar content by <a href=""><strong>subscribing to Decoded, our YouTube channel</strong></a><strong>!</strong></p><img src="" width="1" height="1" alt=""><hr><p><a href="">JavaScript Under The Hood Pt. 6: Asynchronous Callbacks</a> was originally published in <a href="">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  71.        </item>
  72.        <item>
  73.            <title><![CDATA[JavaScript Under The Hood Pt. 5: Prototype and Prototypal Inheritance]]></title>
  74.            <link></link>
  75.            <guid isPermaLink="false"></guid>
  76.            <category><![CDATA[coding]]></category>
  77.            <category><![CDATA[software-development]]></category>
  78.            <category><![CDATA[software-engineering]]></category>
  79.            <category><![CDATA[javascript]]></category>
  80.            <category><![CDATA[programming]]></category>
  81.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  82.            <pubDate>Mon, 12 Oct 2020 02:06:14 GMT</pubDate>
  83.            <atom:updated>2020-10-14T20:08:46.340Z</atom:updated>
  84.            <content:encoded><![CDATA[<figure><img alt="" src="*_G5jXmOOMLv5kIHlxGUJDw.png" /></figure><p>Have you ever seen .prototype attached to an answer in a Stack Overflow post, thought &quot;abort!&quot;, and pressed the back button immediately? Well, you don’t have to worry about this anymore. This article examines what a prototype is, what prototypal inheritance is, and how it can benefit your JavaScript programming greatly.</p><h3>Why is understanding the prototype, prototypal inheritance, and the prototype chain important?</h3><p><strong>Understanding prototypal inheritance</strong> will help you immensely in making your code clean and simple. Most importantly, it will help you to understand the relationships between objects, how these relationships work under the hood, and the potential that this presents. Furthermore, this knowledge also helps in working with legacy codebases as it’s much more common to see .prototype used in past versions of JavaScript (but that doesn&#39;t make this concept any less important to understand).</p><h3>What does inheritance mean?</h3><p>Simply put, you can think of inheritance as an object getting access to the properties and methods of another object. That’s it.</p><blockquote><em>Inheritance is when an object gets access to the properties and methods of another object.</em></blockquote><p><strong>It’s important to note, however, that inheritance in JavaScript is different than inheritance in many other programming languages</strong> (such as C# or Java). While these other languages use something called “Classical Inheritance” (friend/protected/private/interface/etc.), JavaScript uses “Prototypal Inheritance”.</p><p><a href="">According to Wikipedia</a>, prototype-based programming is “a style of object-oriented programming in which behavior reuse is performed via a process of reusing existing objects that serve as prototypes. This model can also be known as prototypal, prototype-oriented, classless, or instance-based programming.”<strong> </strong>Sound a bit complicated? Don’t worry, once you understand the concepts behind this, it will all make sense. Prototypal inheritance is flexible, extensible, and easy to understand.</p><p>For an even more in-depth explanation, see this Mozilla article on <a href="">inheritance and the prototype chain</a>.</p><h3>What is “The Prototype”?</h3><p>In JavaScript, all objects (including functions) have access to many built-in properties and methods. One of these is the <strong>prototype property.</strong></p><p><strong>The prototype property is simply a reference to another object.</strong> In other words, when an object can access properties and methods from another object (with the dot operator, etc.), that object would be its “prototype”. The prototypes can point to other prototypes, and those prototypes to other prototypes, and on and on — this is what is called the <strong>prototype chain</strong>.</p><h3>What is the prototype chain?</h3><p>Let’s say that you’re trying to grab a property or method using the dot operator, but the property or method isn’t available directly on the object (the prototype) that the dot operator is referencing. JavaScript will check that prototype&#39;s prototypes, and that prototype&#39;s prototypes, and work it’s way down the chain until it finds the property or method you are trying to access. If it never finds it, it will throw an error.</p><p>In fact, even separate objects can access one or the other’s prototypes if you want them to; giving you the ability to have multiple objects that have access to the same exact method, with the same exact place in memory.</p><blockquote><em>When trying to access a property or method on another object, if the JavaScript engine doesn’t see the property there, it will work its way down the prototype chain until it finds it (or doesn’t).</em></blockquote><h4>Makes sense. Let’s see some examples!</h4><p>Let’s make a person object that has two properties and a method, and another object that has the same properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now, let&#39;s do something you should <strong><em>never do</em> </strong>but is a good example of how this invisible “prototype” property works. Let’s set the universal __proto__ property (there&#39;s a reason it&#39;s named so weirdly; it makes it near impossible to name a variable that by accident) that all modern browsers give to objects. Actually doing this in real life can cause major performance issues, <strong>so don&#39;t do this!</strong></p><h4>Remember, NEVER do this!</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now, even though john and person are two completely different objects, john inherits from person. So, if we try to access a property on john that doesn&#39;t exist on john, the JavaScript engine will now go to person to find it.</p><p>john already has the firstname and lastname properties, so the JavaScript engine stops there when we tell it to find these properties. It doesn&#39;t need to go to the prototype because it&#39;s already found them.</p><p>If john <strong><em>didn&#39;t</em></strong> have a lastname property, then when we call john.getFullName() we would see &quot;John Default&quot; returned since there isn&#39;t a lastname property on john itself, but its prototype, person, does have this property, with a value of Default.</p><p>This __proto__ property is essentially what invisibly links objects together. Once we get to the very end of the prototype chain, there is a base __proto__ (also called the base object). If we get towards the end of the prototype chain (right before the base object), our __proto__ property will have different methods based on the type of object it is connected to.</p><p>For example, an array’s final __proto__ property has the methods push, pop, reduce, etc. Do these methods look familiar? Well, they&#39;re just built-in methods on the end of the prototype chain for an array!</p><p>The reason these methods are always readily available to you is because the JavaScript engine knows that your array doesn’t have a push property when you call arr.push(). So it goes down the prototype chain, finds it, and executes the method on your array.</p><h3>Manually setting a prototype</h3><p>We can use .prototype to &quot;legally&quot; set the prototype of an object without using the __proto__ object.</p><p>From the W3Schools article <a href="">JavaScript Object Prototypes</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>This is something you’ve probably seen a lot in frameworks, libraries, Stack Overflow posts, and more. Now you know exactly what it’s doing! <strong>It’s setting a new method to a constructor’s prototype so that any objects that have the constructor as a prototype (objects that stem from this function constructor in this case) will have access to the method. </strong>Obviously, they still have access to every property in the constructor as well. While these objects might not directly have this method, they can still access it down the prototype chain.</p><h3>Conclusion</h3><p>Here’s what we’ve covered in this article:</p><ul><li><strong>Every object has something called a “prototype”.</strong> A prototype is an object connected to an object that allows it to access properties and methods from another, related object.</li><li><strong>Prototypal inheritance </strong>is allowing an object to access the methods and properties of another object by using prototypes<strong>.</strong></li><li><strong>The JavaScript engine uses something called the “prototype” chain to access properties and methods on objects.</strong> If we try to access a property or method on an object that doesn’t directly have the property or method, the JavaScript engine will look at the prototype of each object, going all the way down the chain, until it finds it or doesn’t.</li></ul><p>How has gaining an understanding of the prototype, prototypal inheritance, and the prototype chain informed your programming? Let us know in the comments. For more bite-sized advanced JavaScript knowledge, feel free to check out the rest of the series!</p><img src="" width="1" height="1" alt=""><hr><p><a href="">JavaScript Under The Hood Pt. 5: Prototype and Prototypal Inheritance</a> was originally published in <a href="">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  85.        </item>
  86.        <item>
  87.            <title><![CDATA[JavaScript Under The Hood Pt. 4: Bind(), Call(), and Apply()]]></title>
  88.            <link></link>
  89.            <guid isPermaLink="false"></guid>
  90.            <category><![CDATA[software-engineering]]></category>
  91.            <category><![CDATA[javascript]]></category>
  92.            <category><![CDATA[coding]]></category>
  93.            <category><![CDATA[programming]]></category>
  94.            <category><![CDATA[software-development]]></category>
  95.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  96.            <pubDate>Mon, 05 Oct 2020 02:47:40 GMT</pubDate>
  97.            <atom:updated>2020-10-20T19:08:51.564Z</atom:updated>
  98.            <content:encoded><![CDATA[<figure><img alt="" src="*y-tDC-CQ_WIF_GPelr-qHg.png" /></figure><p>When I first got into writing JavaScript, if there was anything that made me scratch my head the most it was the concepts of .bind(), .call(), and .apply(). The problem is that, as with many intermediate/advanced JavaScript concepts, they’re often taught in a way that makes them seem more complicated than they need to be.</p><p>My goal here is that, by the end of this article, you’ll no longer need to scratch your head at these three concepts and — in fact — be able to explain them to others.</p><h3>What are bind(), call(), and apply()? How do they work?</h3><p>To answer this question it’s important to first remember that, <strong>in JavaScript, all functions are objects. This means that they can have properties and methods, just like any other object</strong>. Functions are a special kind of object in that they come with a variety of built-in properties (having a code property that is invocable, having an optional name, and the three methods call(), apply(), and bind()).</p><blockquote><em>Functions are a special type of object in that they come with a variety of built-in properties and methods, three of which are call(), apply(), and bind().</em></blockquote><h3>.bind()</h3><p>Let’s create a person object with two properties and a method. The method will be a getFullName() function expression that uses the &#39;this&#39; keyword.</p><p><strong>Important side note:</strong> In a method (a function property in an object), the ‘this’ keyword actually points to the object it is contained in, NOT the function itself (this is a weird and sometimes frustrating part of JavaScript that can result in hard-to-catch bugs — but not for you.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now let’s create a logName() function that exists outside our person object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>If we call logName() right now, we get an error. This is because logName() is defined in the global scope, so &#39;this&#39; is pointing at the global object, which does not have a getFullname() method. If you’re not familiar with the global object and/or global environment, I’d encourage you to look over my post on the subject <a href="">here</a>.</p><figure><img alt="" src="*P8UE2vDEJcvTq5wb1SePTA.png" /></figure><p><strong>Wouldn’t it be nice if we could control what the ‘this’ keyword points to?</strong></p><p>Enter bind().</p><p>Let’s create a new function called logPersonName() that uses the built-in .bind() property on our logName function object. <strong>Whatever object we pass as an argument to .bind() becomes what the &#39;this&#39; variable points to when the function is run.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Oh, look! Now our ‘this’ variable is pointing to the person object, accessing its properties and working exactly as expected.</p><figure><img alt="" src="*Wv6QCRrPKzWuOtVh7p89BQ.png" /></figure><p><strong>Notice that we aren’t invoking the function before we call </strong><strong>.bind().</strong> Remember what we said at the beginning. Functions are objects, which means that they don&#39;t need to be immediately invoked. <strong>We&#39;re using the function as an object and accessing its built-in bind() property.</strong> This is why we&#39;re writing logName.bind() and <strong>not</strong> logName().bind() . The latter would be <strong>invoking</strong> the function and trying to access a .bind() method on the return value, which it obviously does not have.</p><blockquote><em>Whatever object we pass as an argument to .bind() becomes what the ‘this’ variable points to when the function is ran.</em></blockquote><p><strong>The bind() function returns a new function.</strong> It makes a copy of logName() and tells the JavaScript engine: &quot;Whenever this copy of logName() is invoked, set its &#39;this&#39; keyword to reference person during its execution context&quot;. This behavior of <strong>returning a new function/making a copy</strong> is different than call() and apply(), which we will get to momentarily.</p><p>Now that we have a copy of our logName() function referencing the person object (logPersonName()), <strong>let&#39;s utilize its arguments.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now we get:</p><figure><img alt="" src="*3sbxDdLgGNNDPxGNRsVbqQ.png" /></figure><p><strong>One last quick note about bind()</strong>: We can only call bind() on a function once. Trying to use it subsequently will not do anything.</p><p>Example (Thanks to <a href="">Krusader</a> for providing this example):</p><pre>function printGreetings () {<br>    return console.log(this.phrase);<br>};</pre><pre>const dataGreetings = {<br>    phrase: &quot;Hello World!&quot;,<br>};</pre><pre>const dataFarewell = {<br>    phrase: &quot;Goodbye for now!&quot;,<br>};</pre><pre>// first attempt to bind printGreetings to dataGreetings<br>const printHello = printGreetings.bind(dataGreetings);</pre><pre>printHello();<br>// -&gt; &quot;Hello World!&quot;</pre><pre>// second attempt won&#39;t change anything<br>const printFarewell = printHello.bind(dataFarewell);</pre><pre>printFarewell();<br>// -&gt; can&#39;t be bound twice so will print: &quot;Hello World!&quot;</pre><h3>.call()</h3><p>call() is similar to bind() in that it allows you to pass in what you’d like a ‘this’ value to point to. Except <strong>call() doesn’t make a copy. It invokes the function immediately.</strong> Allowing you to pass in the ‘this’ reference and any arguments while calling the function simultaneously.</p><p>Let’s try calling logName() by using call(). We&#39;ll let it know to reference person as its &#39;this&#39; variable and give it two languages as arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Here’s what we’re left with again:</p><figure><img alt="" src="*oRwhngxRn_ZFnJl0BVut7A.png" /></figure><p>Look similar? While it is similar, it’s <strong>not the same at all</strong>. We’re given the same return value as with bind() above, except this time we didn’t make a copy and call the function immediately.</p><blockquote><em>Unlike bind(), call() doesn’t make a copy of a function. It allows you to pass in the ‘this’ reference and any arguments, and then immediately invokes the function.</em></blockquote><h3>.apply()</h3><p>This one’s easy. It does the <strong>exact same thing as call(). Except for one difference.</strong></p><p>Let’s try replacing call() with apply() and see what happens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><figure><img alt="" src="*WBhlXYx4dO1jLa1UQAeIzw.png" /></figure><p>Hmm. Strange error. But it makes sense. <strong>Apply() does the exact same thing as call(), but it requires the original function’s arguments to be passed in as an array.</strong></p><p>Here’s how it <em>should</em> look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><blockquote><em>Apply() does the exact same thing as call(), but it requires the original function’s arguments to be passed in as an array.</em></blockquote><p>So why would you ever use apply()? Well, it depends on how you’d like your data to be shown. Having the arguments as an array can be useful for mathematical situations, or simply for making the separation between the ‘this’ reference and the original function arguments easier to distinguish.</p><h3>When would I ever use this?</h3><p>A couple main uses for bind(), call(), and apply() are <strong>function borrowing and function currying</strong>.</p><h4>Function borrowing example:</h4><p>Function borrowing involves ‘borrowing’ a method from an object and applying it to another object. Can you think of how call() or apply() might be useful for this?</p><p>person.getFullName.apply(person2).</p><p>We’ve accessed our getFullName() method from person and then used apply() to specify that we&#39;d like the &#39;this&#39; variable to point to a person2 object who will most likely have different first and last name properties (although the property names need to match up).</p><h4>Function currying example:</h4><p>Function currying creates a copy of a function with some preset parameters. Can you think of how bind() might be useful for this?</p><p>A simple example could be creating a function that multiplies two parameters. With function currying bind(), we can create copies of this function with two as a preset parameter.</p><p>function multiply(a, b) =&gt; {return a * b}</p><p>var multiplyByTwo = multiply.bind(this, 2)</p><p><strong>Giving parameters to bind() sets permanent values to the passed in parameters when the copy is made.</strong> So in this case, we’re setting the first parameter to always be 2. Ex: multiplyByTwo(4) would return 8.</p><p>This concept can be very useful for mathematical situations that can benefit from some fundamental functions that can then be built on with other preset parameters.</p><h3><strong>In summary</strong></h3><ul><li><strong>Bind():</strong> Returns a copy of a function, and takes an argument of what you’d like the ‘this’ variable to point to within the copied function. It can take additional arguments that act as permanent preset parameters for its copy of the original function.</li><li><strong>Call():</strong> Is similar to bind() in that it accepts the reference of the ‘this’ variable as an argument, but it calls the function immediately and does not create a copy.</li><li><strong>Apply():</strong> Works almost exactly the same as call(), except any arguments from the original function need to be passed as an array (this doesn’t include the ‘this’ reference, which is outside the array).</li></ul><p>When have you used .bind(), .call(), and .apply() in your programming? Let me know in the comments section.</p><p>If you liked this bite-sized piece of advanced JavaScript, feel free to check out the rest of the series!</p><img src="" width="1" height="1" alt=""><hr><p><a href="">JavaScript Under The Hood Pt. 4: Bind(), Call(), and Apply()</a> was originally published in <a href="">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  99.        </item>
  100.        <item>
  101.            <title><![CDATA[JavaScript Under The Hood Pt. 3: Narrowing With Logical Operators]]></title>
  102.            <link></link>
  103.            <guid isPermaLink="false"></guid>
  104.            <category><![CDATA[programming]]></category>
  105.            <category><![CDATA[software-engineering]]></category>
  106.            <category><![CDATA[javascript]]></category>
  107.            <category><![CDATA[software-development]]></category>
  108.            <category><![CDATA[coding]]></category>
  109.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  110.            <pubDate>Mon, 28 Sep 2020 00:20:48 GMT</pubDate>
  111.            <atom:updated>2020-10-20T19:33:16.728Z</atom:updated>
  112.            <content:encoded><![CDATA[<figure><img alt="" src="*doRG1DYb9XY4_saNhG7BKA.png" /></figure><p>|| (Logical OR) and &amp;&amp; (Logical AND) are very common operators used in JavaScript. But do you know <em>why</em> they work the way they do and how else they can be used? Not only that, but are you aware of their pitfalls? Logical OR and Logical AND can actually cause hard-to-find bugs in your code if you’re unaware of how they work under the hood.</p><blockquote>Logical OR and Logical AND can cause hard-to-find bugs in your code if you’re unaware of how they work under the hood.</blockquote><p>Aside from their popular uses, Logical OR || and Logical AND &amp;&amp;can actually be used fairly easily and efficiently to <strong>replace simple conditional statements</strong>, and often can reduce them down to one line.</p><p>In this article, we will discuss how these two operators work under the hood, how/when they can be used to replace conditional statements, and go over their pitfalls.</p><h3>How do Logical OR and Logical AND work under the hood?</h3><p>First, if we take a look at <a href="">Mozilla’s Operator Precedence table</a> (scroll down a bit to get to the table), we can see that these both have <strong>left-to-right associativity (commonly referred to as “left associativity”)</strong>, which in essence means the JavaScript engine reads whatever is on the left side of the operator first before whatever is on the right side. This will be important in the points to follow. (If you want to read a little more on operator associativity, check out this <a href="">Wikipedia article</a>)</p><p>Before we move forward, I’d like to give a bit of credit to <a href="">Execute Program’</a>s course on TypeScript. While this article isn’t about TypeScript, much of these concepts are explained during their course.</p><p>To understand how || and &amp;&amp;can create unforseen bugs, lets briefly go over falsey values in JavaScript.</p><h4>Falsey values in JavaScript</h4><ul><li>false</li><li>0</li><li>0n (Used with “BigInt” in ECMAScript 2020)</li><li>&#39;’</li><li>undefined</li><li>null</li><li>NaN</li></ul><p>All other values are truthy.</p><p>Can you guess why some of these can cause unexpected bugs with the operators we’re discussing?</p><p>Usually we think of &amp;&amp; as a means to work on boolean values.</p><pre>true &amp;&amp; false<br>//false</pre><pre>false &amp;&amp; false<br>//false</pre><pre>true &amp;&amp; true<br>//true</pre><p><strong>&amp;&amp; returns the first falsey value that it sees. But if both values are truthy, it returns the value on the right</strong> (remember &amp;&amp; uses left associativity).</p><pre>1 &amp;&amp; 2<br>//2</pre><pre>undefined &amp;&amp; 2<br>//undefined</pre><pre>2 &amp;&amp; false<br>//false</pre><pre>null &amp;&amp; 2<br>//null</pre><pre>true &amp;&amp; “hello”<br>//”hello”</pre><blockquote>&amp;&amp; returns the first falsey value that it sees. But if both values are truthy, it returns the value on the right</blockquote><p><strong>Logical OR </strong><strong>||</strong> works similarly, but <strong>returns the first truthy value it sees. But if both values are falsey, it returns the value on the right</strong></p><pre>1 || 2<br>//1</pre><pre>undefined || 2<br>//2</pre><pre>“hello” || null<br>//”hello”</pre><pre>false || null<br>//null</pre><blockquote>|| returns the first truthy value it sees. But if both values are falsey, it returns the value on the right</blockquote><h3>How can Logical OR and Logical AND be used as conditional statements?</h3><p>Using what we now know, let’s answer that question.</p><p>First, let’s use a simple ‘if else’ statement to add 1 to x if x is truthy, then use the Logical AND operator to achieve the same goal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now let’s do the same thing but change x to undefined (a falsey value).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>See what’s going on here?</p><p>In the first example, the JavaScript engine checks the left side of the Logical AND and sees x is truthy, so it checks the right side next. It then sees x again, which is still truthy, so the Logical AND returns 2 (since x === 2). Then the JavaScript engine sees + on the same line (which also has left-to-right associativity), so it adds what’s on the right side of +(which is 1) to what &amp;&amp; returned (which was 2) and returns 3.</p><p>In the second example, the JavaScript engine checks the left side of the Logical AND and sees x, which is now a falsey value undefined. So it stops right there and returns the falsey value, undefined.</p><p>Let’s try it with Logical OR || (remember it returns the first truthy value it sees, or the second value if both are falsey).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>In the last example, || returns 5 since it’s immediately a truthy value. The expression on the right doesn’t even get seen.</p><p>Now let’s make x falsey.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p><strong>These concepts are powerful.</strong></p><p><strong>Let’s step it up a notch</strong> and write a couple of things that are a little more complicated.</p><h4>Write a function that you know will either take in an array or null. If the value is an array, return the length of the array, else return the value.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>The second function using &amp;&amp; is much shorter and concise (albeit the tradeoff is it’s a little harder to understand).</p><p>Now let’s use the Logical OR operator as a conditional for another example.</p><h4>Write a function that takes a value. If the value is truthy, return the value, else return -1.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h3>When || and &amp;&amp; are dangerous</h3><p>Recall our list of falsey values above. <strong>A big problem in JavaScript is that </strong><strong>0 and </strong><strong>&#39;’ are falsey values</strong>. You can imagine how this could cause some confusion!</p><p><strong>Let’s create a function using </strong><strong>|| but break it in a way that could go unnoticed to the rest of your team.</strong> (Assume this function will either take a number or undefined.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>It returned -1! But 0 is a number to us humans!</p><blockquote>A big problem in JavaScript is that 0 and ‘’ (empty string) are falsey values.</blockquote><p><strong>One simple way of dealing with this</strong> is if you think a variable may end up as 0 or ‘’, to opt for using a simple if/else statement.</p><p>Example:</p><pre>let defaultInt = 0</pre><pre>if (defaultInt === 0) {<br>    return 1<br>} else {<br>    return defaultInt + 1<br>}<br>// 1</pre><p><strong>Another, more succinct way to accomplish the same goal would be to use the ES2020 nullish coalescing operator (??).</strong> Which, on the <a href="">Mozilla developer page</a>, is described as so: <em>“The </em><strong><em>nullish coalescing operator (</em></strong><strong><em>??)</em></strong><em> is a logical operator that returns its right-hand side operand when its left-hand side operand is </em><em>null or </em><em>undefined, and otherwise returns its left-hand side operand.”</em></p><p>Example from the documentation:</p><pre>const foo = null ?? &#39;default string&#39;;<br>console.log(foo);<br>// expected output: &quot;default string&quot;</pre><pre>const baz = 0 ?? 42;<br>console.log(baz);<br>// expected output: 0</pre><p>Essentially, it will treat 0 and ‘’ as more or less “truthy” values, which won’t lead to any unexpected behavior like the logical OR operator might.</p><p>So, in summary, Logical OR and Logical AND can be useful in simplifying simple conditional expressions. However, it takes a good understanding of how they work under the hood to take advantage of them, as well as not cause confusion for your team.</p><p><strong>Do you ever use logical operators as conditional statements in your programming? Has it ever caused any unseen bugs for you?</strong></p><p>If you liked this article and want more bite-sized advanced JavaScript concepts, check out the rest of the series!</p><img src="" width="1" height="1" alt=""><hr><p><a href="">JavaScript Under The Hood Pt. 3: Narrowing With Logical Operators</a> was originally published in <a href="">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  113.        </item>
  114.        <item>
  115.            <title><![CDATA[What Is Hoisting? JavaScript Under The Hood, Pt. 2]]></title>
  116.            <link></link>
  117.            <guid isPermaLink="false"></guid>
  118.            <category><![CDATA[coding]]></category>
  119.            <category><![CDATA[development]]></category>
  120.            <category><![CDATA[software-development]]></category>
  121.            <category><![CDATA[javascript]]></category>
  122.            <category><![CDATA[programming]]></category>
  123.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  124.            <pubDate>Mon, 21 Sep 2020 03:33:18 GMT</pubDate>
  125.            <atom:updated>2020-09-22T00:00:21.122Z</atom:updated>
  126.            <content:encoded><![CDATA[<figure><img alt="" src="*DgsBT6d7q2EFTYoRX4U8OA.png" /></figure><p><strong>Welcome back to the Bite-Sized Advanced Javascript series,</strong> where we discuss advanced JavaScript concepts in an easy-to-understand and concise fashion. In my <a href="">last article</a> in this series, I discussed the Execution Context, Global Environment, and the Global Object. While these concepts are not entirely necessary to understand this article, it could help your understanding a bit, and it’s a quick read.</p><p>It’s often said that hoisting is the JavaScript engine simply moving code to the top of the page before execution, but this isn’t accurate. <strong>Hoisting is how the JavaScript engine</strong> (the ‘under the hood part of JavaScript that you never personally see’) <strong>sets aside memory for the variables and functions that you’ve created. It does this even before it starts executing your code</strong>.</p><p>This happens regardless of where the code you’ve written sits lexically (where it’s physically written in the text editor). This is so that once it does begin executing your code line-by-line, it already has space in memory for the variables you’ve created. Let’s dive into this a bit more so we can elaborate and see how it works.</p><h3>How does hoisting work? Can we see it in action?</h3><p>To answer simply, yes. If you want to follow along, in your code editor, create an app.js file and an index.html file that references app.js in a script tag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now open this file in your browser, and then open your devtools console with Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux). Please note that these instructions are for Chrome. If you’re not using Chrome, a quick Google search should suffice to get to this point. Back in your code editor, let’s go into the app.js file and add the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now save the file, refresh the browser page, and go back to your devtools console. What do you think you’ll see?</p><figure><img alt="" src="*BRwnbc3NkXwkDG8zKg9WdA.png" /></figure><p>If you’re not surprised, good. <strong>We’ll get to the weird stuff in a second. </strong>Now let’s do something a little different. Let’s take the last two lines and call them above where they’ve been defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>What do you think will happen now?</p><figure><img alt="" src="*CU35ljiffLCUqt2hGP7pqw.png" /></figure><p>Wait, why is b() being logged, but a is undefined? And for that matter, why weren&#39;t there any errors thrown?</p><p>The answer is hoisting.</p><p><strong>When the JavaScript engine sees that a variable is going to equal something</strong> (in this case a), <strong>it immediately sets that variable equal to </strong><strong>undefined during hoisting as a placeholder.</strong> It isn&#39;t until the code is executed (and it sees what a actually equals )that it changes from undefined to the value you intended.</p><p>Remember what we said about hoisting, that it involves the JavaScript engine going through all of the code and seeing what is going to need space in memory before it starts executing it line-by-line. This means that <strong>JavaScript is different than other languages in that if you call a variable before it’s defined, it won’t throw an error!</strong> This is one of the biggest knocks on JavaScript and it can cause bugs to go unnoticed for a very long time. Sometimes they can get all the way into production before they’re noticed.</p><blockquote><strong>When the JavaScript engine sees a variable that is going to be assigned a value</strong>, <strong>it immediately sets that variable equal to </strong><strong>undefined during hoisting as a placeholder.</strong> It isn&#39;t until the code is executed and it sees what the variable actually equals that it changes from undefined to the value you intended.</blockquote><p>Something else that is important to remember here is that <strong>undefined is NOT the same thing as “not defined”. Undefined is a value in JavaScript. </strong>This is exactly why an error isn’t thrown because a <em>is</em> defined! It&#39;s defined as undefined! To prove this further, let’s take out the line of code where we define a.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now save the file, refresh the page, and look at your devtools console.</p><figure><img alt="" src="*SF7YfkBi8CjtGl9c5eC61g.png" /></figure><p>Now we are actually given an error. During hoisting, JavaScript didn’t see that a was going to be set to anything, so it didn&#39;t make a placeholder for it. Therefore, when the code is executed, we ARE given an error because a is never defined. Not even as undefined. So I know what you’re thinking: <strong>Why didn’t </strong><strong>b() get set to undefined in either example?</strong></p><h4>Functions and hoisting</h4><p>Here’s something we haven’t mentioned about hoisting: <strong>during hoisting, functions are saved in memory in entirety, even though variables aren’t.</strong> This is why b() worked before it was defined. Confusing right? This is why you should rarely, if ever, rely on hoisting. When you’re working on a team and/or with a massive codebase, this can end up in lots of confusion and bugs down the line.</p><h3>Hoisting happens during the Creation Phase</h3><p>Hoisting happens during what is called the Creation Phase. This is, essentially, when the JavaScript engine is setting everything up so it’s ready to execute your code. JavaScript creates the Global Object, ‘this’, the Outer Environment (all discussed <a href="">here</a>), and then it sets up memory space for any variables and functions you’ve defined (hoisting).</p><blockquote>During the Creation Phase, JavaScript creates the Global Object, ‘this’, the Outer Environment, and then it sets up memory space for any variables and functions you’ve defined (Hoisting).</blockquote><h3>Conclusion</h3><p><strong>In summary</strong>, hoisting is <strong>not</strong> the JavaScript engine moving your code to the top of the page. It is the JavaScript engine setting aside memory space for all of the variables and functions you’ve created throughout your code. It does this during the creation phase and sets variables to the value undefined, while saving functions in their entirety. It isn’t until your code begins to be executed that any variables are set to the value you intended. ALL variables in JavaScript are initially set to undefined.</p><p>If you found this article helpful, feel free to share and/or check out the other articles in the series for more bite-sized advanced JavaScript knowledge! How has hoisting caused confusion for you? Has it ever resulted in any unexpected bugs for you and your team? Let me know in the comments.</p><img src="" width="1" height="1" alt=""><hr><p><a href="">What Is Hoisting? JavaScript Under The Hood, Pt. 2</a> was originally published in <a href="">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  127.        </item>
  128.        <item>
  129.            <title><![CDATA[JavaScript Under The Hood Pt. 1: The Global Object]]></title>
  130.            <link></link>
  131.            <guid isPermaLink="false"></guid>
  132.            <category><![CDATA[software-development]]></category>
  133.            <category><![CDATA[programming]]></category>
  134.            <category><![CDATA[coding]]></category>
  135.            <category><![CDATA[software-engineering]]></category>
  136.            <category><![CDATA[javascript]]></category>
  137.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  138.            <pubDate>Mon, 14 Sep 2020 01:01:30 GMT</pubDate>
  139.            <atom:updated>2020-09-17T19:26:29.734Z</atom:updated>
  140.            <content:encoded><![CDATA[<figure><img alt="" src="*tNfAAz39X-p66CHu4NhP4Q.png" /></figure><p>As many of us know, the behaviors that JavaScript exhibits can sometimes be a bit, <em>ahem</em>, weird. A while ago I was watching a <a href="">short comical video</a> by Gary Bernhardt on certain wacky behaviors of Ruby and Javascript (Skip to 1:20 for JavaScript) that exposes some of these behaviors in a funny way.</p><p>While this video is hilarious, it’s worth noting that many of these strange behaviors can actually be understood with a deep understanding of how the JavaScript engine works behind the scenes. And, more importantly than allowing you to demystify video memes, <strong>this understanding will allow you to solve certain bugs that the rest of your team might find strange or hard to track down.</strong> This is one of the most common knocks on JavaScript. Its’ sometimes strange and unexpected behavior.</p><p>What most programmers don’t realize is that, <strong>while JavaScript may look similar to other languages on the surface, deep down it’s actually much different.</strong></p><p>The goal of this series is to turn these unexpected behaviors into, for you, something to be expected. And, just perhaps, allow you to catch strange bugs ahead of time.</p><blockquote>Understanding how JavaScript operates under the hood can allow you to catch strange bugs ahead of time.</blockquote><p>In this article, we’ll be talking about something you may have heard of: the global environment and global object in JavaScript. If you haven’t heard these terms, you will eventually. And, after this, you’ll know exactly what they mean. So what are they exactly?</p><p>Funny you should ask.</p><h3><strong>What are the global environment and global object?</strong></h3><p>Let’s start the answer to this question by giving a little more <strong><em>context</em></strong> on what we call the <strong>execution context</strong>. (See what I did there? So funny you forgot to laugh.)</p><p><strong>The execution context is, essentially, the code that is currently running.</strong> It acts as a “wrapper” around this running code. An example could be a function. When a function is running, it’s acting as the current execution context. <strong>However, the execution context can consist of things that you haven’t written in your code</strong>, such as the global environment and global object, which we will discuss now.</p><p>The most outer wrapper/execution context is the global execution context. When we say “Global” in the world of JavaScript, we’re describing something that is accessible anywhere in your code/not inside a function.</p><p>When you run your code, the JavaScript engine automatically creates two of these things for you: <strong>the global object and ‘this’</strong>.</p><blockquote>“Global” describes anything that is accessible anywhere in your code/not inside a function. JavaScript automatically creates two such things for you: the Global Object and ‘this’.</blockquote><h3><strong>Let’s see this in action</strong></h3><p>If you want to follow along, in your code editor, try making a generic HTML file that uses a script tag to source from another file called app.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Create app.js and leave it totally blank to start.</p><p>Now open this file in your browser (I like to use the <a href="">Live Server</a> extension in VSCode for these kinds of things, but it’s not a necessity.), and open your dev tools console with Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux). (These instructions are for Chrome. If you’re not using Chrome and/or VSCode, a quick Google search will suffice to get to this point).</p><p><strong>So, app.js is completely empty, what do you think is going to show up in our dev console?</strong> If you said nothing, you’re absolutely right. But wait, JavaScript creates the global object and ‘this’ for us automatically upon execution, so we should be able to access that, right? Yes, let’s take a look at it.</p><p>Go ahead and enter ‘this’ into your console. Look what pops up:</p><figure><img alt="" src="*u0G7yrhlejR3LhT2HyqWYA.png" /></figure><p>Hmmm… Now enter ‘window’:</p><figure><img alt="" src="*YF1__F7Ruw7DyDXZZN_QKA.png" /></figure><p><strong>Even though there was no code in the file, JavaScript was still able to execute it and create a global execution context as well as the global object</strong> (‘this’ or ‘window’).</p><p>Okay, that’s all well and good. So <strong>what happens when we put some code in?</strong></p><p>In app.js create a variable with a value, and create an empty function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>Now save the file, refresh the page, and let’s open the dev console again.</p><p>Enter ‘window’ again and click the right-facing triangle on the left to expand the object.</p><figure><img alt="" src="*OL8wGLwdt-17lr1PFcBDog.png" /></figure><p>Here we see a ton of name/value pairs (objects) and, wait a sec, <strong>we see that </strong><strong>a is now in here as well! And for that matter, </strong><strong>b() too!</strong> (If you’re following along and you don’t see it in the same spot as the screenshot, scroll down a ways and you should find it.)</p><p>When we run this file, a global execution context is created. Since a and b()aren’t inside functions (globally accessible), they get attached to the global object.</p><p>Anything defined globally is attached directly to the global object.</p><p>To prove even further that these are attached to the global object, <strong>let’s try entering ‘window.a’ and ‘window.b’ and see what happens.</strong></p><figure><img alt="" src="*_uPM3V-CYeXLLLpWyBv2tg.png" /></figure><p>So, in summary, JavaScript has something called execution contexts, which decide which code is currently running. It has a “global execution context” and a “global object”, which is created for you by the JavaScript engine.</p><p>“Global” in JavaScript describes anything that is outside a function. <strong>The global object is directly attached to anything you declare globally.</strong></p><p>More advanced JavaScript knowledge and how these concepts play into it to come!</p><p>If you enjoyed this bite-sized bit of advanced JavaScript knowledge and are looking forward to more, feel free to share!</p><p>How has understanding the global environment and global object helped you in your programming?</p><img src="" width="1" height="1" alt=""><hr><p><a href="">JavaScript Under The Hood Pt. 1: The Global Object</a> was originally published in <a href="">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  141.        </item>
  142.        <item>
  143.            <title><![CDATA[Understanding Singly Linked Lists and their functions]]></title>
  144.            <link></link>
  145.            <guid isPermaLink="false"></guid>
  146.            <category><![CDATA[software-development]]></category>
  147.            <category><![CDATA[javascript]]></category>
  148.            <category><![CDATA[coding]]></category>
  149.            <category><![CDATA[software-engineering]]></category>
  150.            <category><![CDATA[programming]]></category>
  151.            <dc:creator><![CDATA[Colton Kaiser]]></dc:creator>
  152.            <pubDate>Mon, 06 Jul 2020 01:47:34 GMT</pubDate>
  153.            <atom:updated>2020-07-07T01:15:58.180Z</atom:updated>
  154.            <content:encoded><![CDATA[<h3>Understanding Singly Linked Lists and Their Functions</h3><figure><img alt="" src="*iiEWrP2IznA6HbmuIdK0lQ.png" /><figcaption>Structure of a singly linked list</figcaption></figure><p>Linked lists are something we’ve all heard of, and for good reason: <strong>They serve as a base understanding for all other data structures.</strong> There are two different kinds of linked lists: Singly linked lists and Doubly linked lists. In this article, we’ll be discussing the former (and we’ll provide a brief comparison of both).</p><p><strong>Before moving forward:</strong> An understanding of ES2015 JavaScript “Class” and “Instance Methods” syntax is required for this article. If you’ve never heard of or used JavaScript Classes, this information will be very hard to understand (as will many other data structures besides linked lists). If this is the case, do a bit of research and then come back! If you’ve got an understanding of this syntax, then let’s jump right in.</p><h3><strong>What is a singly linked list?</strong></h3><figure><img alt="" src="*6ReSYwX-z-n4jWPCRSxqBw.png" /><figcaption>Fig. 1: Structure of a singly linked list. Credit: <a href=""></a></figcaption></figure><p><strong>A singly linked list is a data structure that contains a head, tail, and length property </strong>(the last is optional, although it makes things much easier).</p><p>Linked lists consist of something called <strong>nodes.</strong> <strong>A node is a piece of data that has a value as well as a pointer to another node or null. </strong>The head of a linked list is the very first node, and the tail is the very last node, which will always point to null.</p><blockquote>A singly linked list is a data structure that consists of nodes. Each node has a value and a pointer that points to the next node, or null once it gets to the end.</blockquote><p>The difference between a singly linked list and a doubly linked list is as follows:<strong> In a singly linked list, each node only points the node in front of it (or next in line). In a doubly linked list, each node also has a pointer that references the one behind it.</strong> As such, singly linked lists provide an easier base understanding of the linked list data structure as a whole.</p><p>It’s important to mention that, unlike an array, <strong>linked lists do not have built-in indexes. </strong>This means that in order to find a specific point in the linked list, you need to start at the beginning and traverse through each node, one by one, until you find what you’re looking for.</p><p>Here’s an interesting analogy I once heard: A linked list is like a skyscraper with no elevators. To get to the floor you’re looking for, you need to climb up the stairs one level at a time. In an array, you can press a button that takes you right to the floor you need to get to.</p><p>You’re probably thinking: “Linked lists sound very complicated and inefficient, which would I ever use them?” Well, let’s talk about it.</p><h3><strong>Why/when would I use a singly linked list?</strong></h3><p>There are a few different times linked lists shine above arrays, and vice-versa. It depends on what exactly you’ll be doing with the data.</p><h4><strong>Inserting or deleting data at the beginning of a list</strong></h4><p>Remember that arrays come with built-in indexes. This means that if an array has a thousand items in it and we need to place an item at the very beginning of an array, every single index in the entire array needs to be shifted to the right and incremented (which means we would have an O(n) here, but we will come back to the Big O of arrays vs linked lists at the end of this article).</p><p>In a linked list, adding data to the beginning is extremely simple and efficient. You just need to tell the new piece of data to point to the head, and then assign that piece of data to be the new head. No re-indexing required.</p><h4><strong>Inserting or deleting data somewhere in the middle of a list</strong></h4><p>Same as the reason above, insertion and deletion of data in a linked list doesn’t require re-indexing the entire list, which makes it faster than inserting or deleting data in an array (unless of course you’re adding or deleting something from the very end of an array, which would not require any re-indexing.)</p><blockquote>Linked lists are very useful when working with insertion and deletion of data. Arrays are more useful when random access is required.</blockquote><p>Okay, now that we have a brief understanding of what singly linked lists are and the rationale behind using them. <strong>Let’s create one and build out its functions.</strong></p><p><strong>Important: </strong>There are many ways of building out any of these functions. These are all just one way to do each. So if you’ve seen them done differently elsewhere, neither way is wrong. But if you’ve found a better solution to any of them, feel free to share in the comments!</p><h4><strong>Creating a singly linked list</strong></h4><p><strong>To create a singly linked list, we will need to start by creating two classes: </strong><strong>Node and </strong><strong>SinglyLinkedList</strong></p><p>Since our nodes consist of some sort of value as well as a pointer to the next one, it needs to contain a val attribute as well as a next attribute. next will start by being equal to null.</p><p>Remember that our singly linked list needs to include a head and a tail to specify where it begins and ends. We will also add a length property to make some of our functions easier to implement. The head and tail will start as null.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Adding to the end of the list</strong></h4><p>To add to the end of the list, all we need to do is create a new node and set the current tail’s next property to be the new node, then make the new node the tail.</p><p>Don’t forget the <strong>edge case: </strong>if there’s no head (i.e. the list doesn’t exist yet), set the head and the tail to be the new node. Increment the length by one and return the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Removing from the end of the list</strong></h4><p>For this, we will need to loop through the list until we find the tail, then set the next value of the node directly before the tail to be null, and set that node to be the new tail. Then decrement the length of the list by one and return the value of the node that was removed (remember you’ll need to save this variable ahead of time in order to return it).</p><p><strong>Edge cases:</strong> If there’s no head, return undefined; and if the length of the list is zero AFTER removing the node, make sure the head and the tail are set back to null.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Removing from the beginning of the list</strong></h4><p>Removing a node from the beginning of a singly linked list is very simple. All we need to do is set the head to be the next value of whatever the current head is, then decrement the length by one and return the old head (remember to save the original head as a variable so you can return it.)</p><p><strong>Edge cases: </strong>The edge cases for shift() are<strong> </strong>very similar to pop(). If there’s no head, return undefined. If the length of the list is zero AFTER removing the head, make sure the tail is set back to null (the head will already be set to null in this case, but the tail will be set to Node by default. Setting it to null prevents this from happening).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Add to the beginning of the list</strong></h4><p>Adding to the beginning of a singly linked list is also very easy. We just need to create a new node and set its next value to be the current head, assign it to be the new head, increment the list by one, and then return the list.</p><p><strong>Edge case: </strong>If the head is currently null, then that means what we’re unshifting is going to be the only value in the list. Therefore it will need to be set to be the head as well as the tail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Retrieve a node by its position in the list</strong></h4><p><strong>Remember, linked lists don’t have indexes for their values like arrays! So we will need to do some extra work here. </strong>Our function will be passed an index, so we will need to create some sort of counter variable that we can use to loop through the list (starting at the head) while it’s less than the index. Once we reach the index that’s been passed in, we return that node.</p><p><strong>Edge case: </strong>If the passed in index is less than zero OR if it’s greater than or equal to the length of the list, return null (or -1, undefined, etc. (something bad)).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Change the value of a node given its position in the list (and the new value)</strong></h4><p>Since we’ve already created our get function, we can use this to find the node at the given index. We can set this node to a variable easily since our get function returns the found node. Once we’ve found the node, all we need to do is set its value to the passed in value, and then return true. If it doesn’t find a node, return false.</p><p><strong>Edge case: </strong>The get function we’ve defined will already take care of invalid indexes. This allows our set function to be very concise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Add a new node to the list at a specified position</strong></h4><p>This function is a bit tricky. First, we will need to create our new node given the passed in value. Now, in order for us to insert our node somewhere, we will need to find whatever node is directly before the passed in index, and set its next value to be the new node. After this, we need to set our new node’s next value to be what the found node’s next used to be (I know, a lot of “nexts”). This means we will need to make sure we’ve saved this as a variable ahead of time. Once we’ve added the new node, increment the length by one and return true.</p><p><strong>But wait! </strong>IF our function is passing us an index of zero or an index equal to the length of the list, we’ve already written functions for these! Use your unshift or push function in these cases, and pass them the given value.</p><p><strong>Edge cases: </strong>If the given index is less than zero or greater than the length of the list (it doesn’t matter if it’s EQUAL to the length of the list in this case since we can just add the new node to the end), return false. Also, we’d like this function to ONLY return true or false. Right now, if we ended up using our unshift or push methods here, it would return the whole list. This isn’t the end of the world, but as programmers we like to be consistent. An easy workaround here is to make our method return true if either of these methods are used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Remove a new node from the list at a specified position</strong></h4><p>To remove a node, all we need to do is find the node previous to the index passed in, and then set its next to be the next of the next node (the one we’re removing). All we’ve done here is severed the link between the previous node and the one that used to be after it, by making the previous node’s next the one two nexts ahead of it (getting tired of reading the word “next” yet?).</p><p>Once this is done, decrement the length by one and return the removed node (this means you’ll need to have saved it to a variable).</p><p><strong>But wait! </strong>If the passed in index is equal to the length of the list minus one, or if it equals zero, we’ve already written methods for these! In these cases, return your pop() or shift() methods, respectively.</p><p><strong>Edge case: </strong>If the passed in index is less than zero OR greater than or equal to the length of the list, return null.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><h4><strong>Reversing a singly linked list in place</strong></h4><p>Reversing a singly linked list in place (“in place” meaning by not making a copy of it) is a classic problem and likewise the hardest to explain. There are also many ways to do it. Here’s how we will solve it <strong>(this is an example of an iterative solution, there are also recursive solutions that work as well)</strong>:</p><p>First, swap the head and the tail, and save the tail as a new variable (often called curr). Then create a variable next and a variable prev. prev should start as null. Next, loop through the list. Set next to be the next property of whatever curr is at the time (it starts as the tail as defined above). Then, set the next property of the curr node to be the prev variable we defined. Now, set prev equal to curr, and curr equal to next.</p><p>Once this is all done, return the updated list.</p><p>Feeling extremely confused? Understandable. Take a look at the solution below and try to understand what’s going on. If you’re still having trouble, I’ve provided a helpful gif under the solution that might help.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href=""></a></iframe><p>If you’re having a hard time understanding this, take a look at the gif below from <a href=""></a>.</p><figure><img alt="" src="*o4QixeDthTcTcZ3dc11cgw.gif" /><figcaption>Fig. 2: Reversing a singly linked list. Credit: <a href=""></a></figcaption></figure><h3><strong>Big O of Singly Linked Lists vs. Arrays</strong></h3><p>Whew! Still with me? Let’s take a second to go over the Big O Notation of singly linked lists vs arrays.</p><h4><strong>Insertion: O(1)</strong></h4><p>Singly linked lists are extremely useful for inserting values at the beginning of a set of data. It doesn’t require any re-indexing like an array does, and therefore takes constant time.</p><h4><strong>Removal: O(1) or O(n)</strong></h4><p>If we’re removing from the beginning of a singly linked list, this is extremely efficient and takes constant time. However, if we’re removing from the very end, we need to find the item right before the tail, which involves iterating through the entire list.</p><h4><strong>Searching: O(n)</strong></h4><p>If we’re looking for a specific value in a singly linked list, this takes linear time due to the necessity of starting at the beginning and looking through the whole list until we find what we’re looking for. This is similar to arrays, although not totally an equal comparison.</p><h4><strong>Accessing: O(n)</strong></h4><p>As discussed at the beginning of this article, accessing a specific index of a singly linked list is not nearly as efficient as an array due to not having built-in “random access” as an array does. Accessing the thousandth element in an array is very simple and takes constant time since every value is indexed, accessing the thousandth item in a singly linked list is much slower and takes linear time due to the reasons discussed above.</p><p>In this article, we covered what singly linked lists are/how they differ from doubly linked lists as well as arrays, what they’re useful for and when an array might be better, common functions of singly linked lists, and the Big O of their use cases.</p><p>We’ve covered a lot in this article. If it seems like a lot, take a while to digest the information and come back and review as much as you need to.</p><p><strong>Got any solutions that are better than the ones provided here? Feel free to share them in the comments!</strong></p><img src="" width="1" height="1" alt=""><hr><p><a href="">Understanding Singly Linked Lists and their functions</a> was originally published in <a href="">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
  155.        </item>
  156.    </channel>
  157. </rss>

If you would like to create a banner that links to this page (i.e. this validation result), do the following:

  1. Download the "valid RSS" banner.

  2. Upload the image to your own server. (This step is important. Please do not link directly to the image on this server.)

  3. Add this HTML to your page (change the image src attribute if necessary):

If you would like to create a text link instead, here is the URL you can use:

Copyright © 2002-9 Sam Ruby, Mark Pilgrim, Joseph Walton, and Phil Ringnalda