<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marc Kirk on Medium]]></title>
        <description><![CDATA[Stories by Marc Kirk on Medium]]></description>
        <link>https://medium.com/@byteslovesbits?source=rss-97f5b7148e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5ZmUUSUImDWB1LNn58QGIQ.jpeg</url>
            <title>Stories by Marc Kirk on Medium</title>
            <link>https://medium.com/@byteslovesbits?source=rss-97f5b7148e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:33:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@byteslovesbits/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Web Components Introduction]]></title>
            <link>https://medium.com/@byteslovesbits/web-components-introduction-27fcfe13d500?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/27fcfe13d500</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 09:57:04 GMT</pubDate>
            <atom:updated>2023-02-18T09:57:04.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oXBHqfOeAa6ufLRY.jpg" /></figure><blockquote>Imagine a world where frameworks dont exist. A world where we dont have to learn yet another framework that promises to solve global-famine and dare I say it, cancer!</blockquote><p>Whilst the promise of curing cancer is extreme language, it highlights a critical problem with web-development. We have become utterly dependant on frameworks!</p><p>For many, frameworks are to development what oxygen is to life. Many developers fear that they cannot build anything useful without a framework. This article will begin to challenge that assertion.</p><h3>The Problem</h3><p>Frameworks are the lay of the land, this is what we developers do. We see a shiny framework, spend months or even years learning said framework, build cool stuff with the framework, only for the framework to wilt into obscurity.</p><p>So what do we do after a framework wilts? We do what has always been done, we find a shinier framework that promises to rid the world of SHIT code. It is a brutal and unforgiving landscape that demoralises even the hardiest of developers.</p><p>So what is the alternative? Enter web-components. A better way to liberate yourself from this dependency hell!</p><h3>Web Components</h3><p>Web components are a fantastic way to build modular software. Backed by web-standards and supported by all major browsers — web-components are constantly evolving to meet our complex needs.</p><p><strong>This article</strong> will walkthrough how to use web-components. We will create a simple &lt;counter-component&gt;that will demonstrate the main features of web-components.</p><h3>Why Learn Web-Components?</h3><p>Simple. They help us to create modular and scaleable software that is backed by standards. They promise to be as future-proof as any framework and will replace most frameworks in most situations — eventually…</p><p>When frameworks arrive on the scene they are shiny and bright. They lure developers in with grand promises — only to wilt into obscurity. Inevitably, to fill the void, we find shinier frameworks that make even grander promises. <em>Add infinitum. </em>This <strong>vicious cycle</strong> is false economy and in the long run wastes our time.</p><h3>What are Web-Components?</h3><p>Web-components are reusable, modular, custom-elements — built by us! Our custom-elements can be used like regular &lt;html&gt;elements. It is a simple concept but they need several technologies to work.</p><h3>Technologies that Make Web-Components</h3><p>Technologies don’t happen in a vacuum and web-components are no exception. To realise the goal of reusable, modular, custom-elements, three technologies are used.</p><ol><li>Custom-Element — JavaScript APIs to define custom-elements and their behaviour(s).</li><li>Shadow-DOM — JavaScript APIs to attach an encapsulated DOM to a custom-element that is similar to but distinct from the document’s DOM.</li><li>HTML-Templates — &lt;template&gt; help to add structure to the custom-elements and are rendered when needed using JavaScript.</li></ol><p>Fortunately, these technologies are standardised in the browser, so one less thing to think about.</p><h3>Creating Custom Elements</h3><p>Let’s create a &lt;counter-comp&gt; custom-element that demonstrates all the features of a web-component.</p><p>Creating and using a custom-element is a <strong>three step process</strong>.</p><ol><li>Create a class to describe your custom-element’s properties and behaviours. Lines 1–7.</li></ol><p>2. Register the custom-element and name it with a hyphen. Line 9.</p><p>3. Add the custom-element to your html page. See Fig below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/527babbcc21f1eb891f8aa090b1a3345/href">https://medium.com/media/527babbcc21f1eb891f8aa090b1a3345/href</a></iframe><p>You add the &lt;counter-comp&gt; element to your html document, just like a regular html element. See below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00f2639f99522f03273a533c31772314/href">https://medium.com/media/00f2639f99522f03273a533c31772314/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4_06x2xMv8uH3S36OOgtNA.png" /><figcaption>Fig— Adding the &lt;counter-comp&gt; element to the HTML markup. Note the $0 which is a reference to the element.</figcaption></figure><p>If you query the &lt;counter-comp&gt; element using JavaScript DOM methods, you’ll see that your custom-element behaves like a regular html element. Gotta love web standards!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*fUd4co8YQU2PQnMcgqbCUA.png" /><figcaption>Fig — Use your custom-element like a regular html-element. Use DOM methods on your shiny new web-component!</figcaption></figure><h3>The Web-Component Life Cycle</h3><p>Inside the custom-element&#39;s class, the Counter Class in our case, we define lifecycle callback methods that fire when the custom-element changes. These methods include the:</p><ol><li>connectedCallback()</li><li>disconnectedCallback()</li><li>attributeChangedCallback()</li></ol><p>Let’s demonstrate the connectedCallback() and disconnectedCallback()lifecycle methods. When the &lt;counter-comp&gt; custom-element is added to the DOM, the connectedCallback() life cycle method is called, which gets the &lt;counter-comp&gt; class value of hello-world and renders the value inside a &lt;h1&gt; element inside the DOM. Two-seconds later, the &lt;counter-comp&gt; custom-element is removed from the DOM, which triggers the disconnectedCallback() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be981f02ba21399f2d36f181a964a88f/href">https://medium.com/media/be981f02ba21399f2d36f181a964a88f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3RqtSXJqK6XevBAU4Oz0fw.gif" /><figcaption>Figure — connectedCallback() and disconnectedCallback() methods firing</figcaption></figure><h3>The Counter-Component</h3><p>Let’s develop the &lt;counter-comp&gt; custom-element. This is a counter with two buttons. One button to increment the counter and one button to decrement the counter. &lt;counter-comp&gt; explores <strong>custom-elements</strong>, <strong>shadow-dom</strong>, <strong>html-templates</strong> and <strong>application-state</strong>. The basic layout can be seen below. We will improve the look with some CSS later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*iZKiU4ZyoaK7lqlqc0rgog.png" /><figcaption>Fig — Unstyled &lt;counter-comp&gt; custom-element</figcaption></figure><p>Let’s create index.html that contains a custom-element named &lt;counter-comp&gt;. line 4 imports counter.js.</p><p>counter.js is the JavaScript class that defines and registers the &lt;counter-comp&gt; custom-element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed9cdb8a70391d3c67c4b8ee5ec6e809/href">https://medium.com/media/ed9cdb8a70391d3c67c4b8ee5ec6e809/href</a></iframe><p>Now turn your attention to counter.js that defines and registers the &lt;counter-comp&gt; custom-element. I include the life-cycle method connectedCallback() and use a console.log() inside the connectedCallback() method to verify that &lt;counter-comp&gt; successfully connects to the document. Note how ${this} refers to the Counter instance itself. Also, I create a crude render() method that renders basic html when the &lt;counter-comp&gt; custom-element is connected to the DOM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a01520f50e61d946026c629b2cabaf84/href">https://medium.com/media/a01520f50e61d946026c629b2cabaf84/href</a></iframe><h3>Shadow-DOM</h3><p>We want our web-components to work as discrete, independent objects. To realise this goal, we need to encapsulate our web-component.</p><p>To encapsulate a web-component into a discrete unit, that operates on its own data, we use the shadow-dom.</p><p>The shadow-dom helps to create a web-component with a single responsibility. Having a single responsibility for a software component is one of hallmarks of quality, easily testable software that scales well.</p><p>The ultimate goal when we encapsulate web-components is to to keep the html markup, cssstyles and JavaScript methods within a web-component separate from other stuff in the DOM. We do this by attaching a shadow-dom to our web-component. The shadow-dom is distinct from the document’s DOM and acts independently. The shadow-dom effectively isolates our web-component.</p><h3>Attaching a Shadow-Dom to a Web-Component</h3><p>Custom-elements and normal-elements can have a shadow-dom-tree attached to them. We then attach other nodes to this shadow-dom-tree to create encapsulated elements.</p><p>Let’s attach a shadow-dom to our &lt;counter-comp&gt;custom-element. This shadow-dom starts at that <strong>shadow-root</strong>. We then attach elements to the shadow-root.</p><p>The shadow-root acts just like the normal dom but it is encapsulated from the dom. We can change nodes inside the shadow-root from the DOM itself but the code within the shadow-root cannot effect anything outside the shadow-dom.</p><p>Let’s attach a shadow-root to our &lt;counter-comp&gt;custom-element. Line 8. Then we attach htmlelements to the shadow-root. Line 13. Note the attachShadow({mode: &#39;open&#39;})method. The value of &#39;open&#39; means that you can access the shadow-DOM with JavaScript from the main-page context. You could access it like so. <strong>Conversly, setting the mode to </strong><strong>&#39;closed&#39; means</strong> you cannot access &lt;counter-comp&gt;&#39;s shadow-dom from the main-page context. You could say it is closed for modification and enables encapsulation.</p><pre>const counterCompShadowDom = doucment.querySelector(&#39;counter-comp&#39;).shadowRoot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-i23LqKlH2--vqnOo7Sog.png" /><figcaption>Fig — Accessing &lt;counter-comp&gt;’s shadow-dom</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f502a55e2eae329e0b340bd5c27f6b2/href">https://medium.com/media/0f502a55e2eae329e0b340bd5c27f6b2/href</a></iframe><h3>Recap</h3><p>We created our own custom-element named &lt;counter-comp&gt; and registered this custom-element so that the browser can attach it to the DOM. We added a connectedCallback() lifecycle method to ease debugging and see what is going on with our custom-element. Finally, we attached a shadow-dom to our custom-element to help facilitate the concept known as encapsulation.</p><p>Stay with me for Part 2 of web-components where we dive into passing data to and from custom elements.</p><p>Please leave a like and comment. See you in the next article. 😁👍❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27fcfe13d500" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to PowerShell Objects]]></title>
            <link>https://medium.com/@byteslovesbits/an-introduction-to-powershell-objects-4a7d168ed6f8?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a7d168ed6f8</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 12:37:52 GMT</pubDate>
            <atom:updated>2023-01-01T12:37:52.760Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In our world of computers, objects help us to get stuff done. Objects vary in complexity, but ultimately — they help solve business problems. This article goes deep into real-world practical applications of PowerShell objects.</blockquote><h3>Defining an Object</h3><p>I will defer the rigorous defintion of an object until later, but for now, an object is:</p><blockquote>Something that gets shit done!</blockquote><p>Whilst this definition lacks rigour, it serves its purpose for now. As we progress through this article, we will reshape and redefine this defintion.</p><p>As you complete each example and gain further knowledge about objects, redefining the definition of an object will help you synthesise the information quicker.</p><h3>Unravelling Objects</h3><p>Let’s unravel objects. Enter the following code into your shell.</p><pre>$processes = Get-Process | Sort-Object -Property WorkingSet -Descending</pre><p>Intuitively, this line of code reads like a sentence. It says, in the variable $processes — store all the processes on the system and sort the processes in <em>‘descending order of memory used’</em>.</p><p>In Figure 1, each process is an object and what Get-Process really does is get an array of process-objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTk3V48yjueA9cvncmjmJQ.png" /><figcaption>Figure 1 — Getting all the processes on the system.</figcaption></figure><p>We can get the individual process-objects by using <strong>bracket notation </strong>to access elements within an array.</p><p>$processes is an array of process-objects and to get the first process-object, we say $processes[0].Figure 2. Remember, arrays typically start at array[0].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*MSO3q5-jzxzkDIfViEIu3g.png" /><figcaption>Figure 2 — Using bracket notation to get the first process-object in the array of process-objects</figcaption></figure><p>When we use the cmdlet Get-Process, the cmdlet returns an array of multiple System.Diagnostics.Process objects. In Figure 3, we see that the first System.Diagnostics.Process is the process with the ProcessName of Creative Cloud.</p><blockquote>PowerShell uses .<strong>net types,</strong> such asSystem.Diagnostics.Process. We will be covering .net types further in the article.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLJ-gW01VOf8oilRu_FswQ.png" /><figcaption>Figure 3 — An array of objects. Each object is a System.Diagnostics.Process object</figcaption></figure><h3>Types of Objects</h3><p>When talking about objects, we are really talking about the types of objects.</p><p>In the real world, there are different types of objects. Cats and Dogs are objects and whilst they share similar properties and behaviours, they are distinct objects. You would never classify a cat as a dog and similarly — a file-object is not a process-object.</p><blockquote>You would never classify a cat as a dog and similarly — a file-object is not a process-object and a process-object is not a date-object…</blockquote><p>In the real-world, objects have <strong>properties and behaviours</strong>. Some properties of a cat might be eye-colour and weight. The cat will also exhibit behaviours such as always landing on its feet. In contrast, dogs do not always land on their feet.</p><p>In PowerShell, objects have properties and methods too. So a file-object might have a property named isReadONly that is set to true or false and a method such as delete that would delete the file-object.</p><p>Let’s redefine what an object is. An object is:</p><blockquote>Something that has properties and methods that helps us to get shit done!</blockquote><h3>Data Types</h3><p>A discussion of objects would not be complete without a basic understanding data-types.</p><p>Many of the things we do in programming revolves around data-types and knowing what data-type we are working with helps us to understand what operations we can do with that data-type.</p><p>In PowerShell, data-types fall into two categories. Value-data-types such as integers or floats and reference-data-types, such as strings, arrays and hash-tables.</p><h3>Find the Type of Object and the Object’s Properties and Methods</h3><p>To interact with objects, we must first find out what type of object we have.</p><p>To do this, we use the Get-Member cmdlet. Get-Member conveniently lists the objects type, the object’s properties and the object’s methods. Collectively, the objects properties and methods are known as the <strong>object’s members.</strong></p><h4><strong>So why would we need list an object’s members?</strong></h4><p>Imagine if you try to classify a cat as a dog and then ask the cat to perform a dog-specific-behaviour. The cat would most likely tell you to go do one because it is a cat and it cannot do dog-specific-behaviours, such as rounding up sheep. In a similar vein, we cannot ask a process-object to give us information about a domain-user because the process-object does not have methods or behaviour to query an active-directory domain controller.</p><h4>Get-Member</h4><p>One of the advantages of PowerShell is usability and not memorisation. Get-Member is the exception and I recommend you commit the cmdlet to memory as it will be extremely useful.</p><p>Let’s find the <strong>type and members of an object!</strong></p><p>Issue the cmdlet Get-Date | Get-Member. What we are really saying here is get a System.DateTime object and pass it onto the Get-Member cmdlet. Get-Member knows exactly what to do with that System.DateTime object.</p><p>Get-Member will then list theSystem.DateTime object’s type, properties and methods. Figure 4. Effortless right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wfYE1glcuaK6D2SARpPQw.png" /><figcaption>Figure 4 — Using the cmdlet Get-Member to get a list of the members (properties and methods) of a System.DateTime object</figcaption></figure><h4>Get a Property of an Object</h4><p>Have a look at all the properties and methods that a System.DateTime object has. Figure 4.</p><p>To query the object’s properties or to invoke a method on the object, we must first surround the cmdlet that returns an object in parentheses - like this(Get-Member).</p><p>Let’s get a property of aSystem.DateTime object. We’ll do this by surrounding the cmdlet (Get-Date)in parenthesis, followed by a (dot) and then, if we know the property name we want, such as Hour, we can type Hour, otherwise we repeatedly hit the tab key to cycle through the System.DateTime object’s properties and methods. Figure 5.</p><p>(Get-Date).Hour</p><p>(Get-Date).Hour will first get a System.DateTime object and then request the Hour property of that System.DateTime object. We’ll also get the Millisecond property twice to illustrate how we are dealing with two distinct System.DateTime objects. Figure 5.</p><p>What we are really saying is — hey System.DateTime object, I want to know what your Hour property is. I also want to know what your Millisecond property is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*i3pvNUQCBcNnLUXWD0O8Aw.png" /><figcaption>Figure 5 — Getting the properties of a ystem.DateTime object.</figcaption></figure><h3>Make the Object do Something</h3><p>Methods are to PowerShell-objects what behaviours are to real-world-objects.</p><p>If a cat can meow and stalk prey, it is intuitive to reason that a Date-Time object cannot meow and stalk prey, but a System.DateTime object has other behaviours or methods such as IsDaylightSavingTime() to test if the date is adjusted for daylight savings time.</p><p>There are many more methods we can call on a System.DateTime object, such as ToUniversalTime() which converts the current System.DateTime object to UTC time. Check out Figure 4 to see if you can reason about what the other methods do.</p><p>To find the properties or methods of an object, we pipe the object to theGet-Member cmdlet with some additional options to retrieve either properties or methods of that object. Figure 6 &amp; Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-dwYZJV7brG3tliAUYDWg.png" /><figcaption>Figure 6 — Using Get-Member to retrieve an object’s properties</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbQew6FAb1SsMq51fMHYvA.png" /><figcaption>Figure 7 — Using Get-Member to retrieve an object’s methods</figcaption></figure><p>Let’s redefine what an object is:</p><blockquote>An object is a type of something that has properties and methods to help us get shit done!</blockquote><h3>.NET Types</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a7d168ed6f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PowerShell Survival Guide Part 3]]></title>
            <link>https://medium.com/@byteslovesbits/powershell-survival-guide-part-3-d01ee66232e5?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d01ee66232e5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Thu, 27 Oct 2022 19:57:19 GMT</pubDate>
            <atom:updated>2022-10-27T20:12:33.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wDP0H8qIFLCNb0Ki.jpg" /></figure><h3>The Usability Champion</h3><p>If two usability experts had a child, they would produce PowerShell! The designers of PowerShell went to extreme efforts to make PowerShell the most user friendly shell in existence. They were considerate of a wide range of use-cases — catering to the needs of not only systems administrators but also developers and end-users.</p><p>PowerShell was designed to HELP us, not hinder us. One of the key factors of successful software is great usability. Many all-singing and all-dancing applications have failed in the market due to horrendous usability and fortunately for us, PowerShell excels at usability.</p><p>Let’s demonstrate this USABILITY.</p><p>Cmdlets take the form verb-noun. For example, to get my current location in the file system, I issue the cmdlet <strong>get-location</strong>. This is similar to the Linux command <strong>pwd</strong>. Pwd does not make intuitive sense, but get-location does. A major advantage of the verb-noun convention is self-documenting code. Self documenting code is clean-code.</p><blockquote>Oh, and for all the Linux users who think typing get-location is too much effort — the PowerShell designers have your back. Just type pwd. It is an alias for get-location. As your scripts increase in complexity, the extra keystrokes and self documenting nature of PowerShell will pay massive dividends down the road. Besides, we can also turn longer cmdlets into shorter ones if needed!</blockquote><blockquote>Clean-code is better code. It makes code readable and understandable by everyone. Now and in the future. Nothing is cryptic. It is self-documenting. Repeat — self-documenting code is better code.</blockquote><p>These intuitive and self documenting cmdlets make it easy to find what you want to achieve from a cmdlet. If you know that cmdlets take the form verb-noun, intuitively, you know how to <strong>get-stuff</strong>. Intuitively, you know how to <strong>set-stuff</strong>. Intuitively, you know how to <strong>read-stuff</strong>. You get the message. Incidentally, if you were to <em>‘get the message’</em> in PowerShell, it would likely take the form <strong>get-message</strong>.</p><p>Get-Date ===&gt; gets the date.</p><p>Set-Date ===&gt; sets the date</p><blockquote>Tip: To get all the verbs that PowerShell uses and recommends for script writers — enter <strong>Get-Verb</strong>. When you write your own scripts, using these verbs ensures you are producing idiomatic-code.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7RLohjLs2fMi3I0fAi3ZA.png" /><figcaption>Figure — Get-Verb gets all the verbs in PowerShell. When you write your own PowerShell functions — sticking to these verbs is idiomatic and intuitive! Deviate if you must, but try not to.</figcaption></figure><h3>Hardly any Memorization</h3><p>Arguably, the best thing about PowerShell is you do not need to memorize hardly anything. When I say hardly anything, I really mean hardly anything. It is almost effortless to get stuff done with little to no prior knowledge of the system.</p><p>Can you guess how you would <em>get all the commands on the system?</em></p><p>Using our verb-noun naming convention, intuitively, we might enter something like get-cmdlet or get-command. Try it out. See what happens.</p><p>Stay with me for part 4 of the PowerShell survival guide, where I introduce the POWER in PowerShell — OBJECTS.</p><p>At the beginning of this article I wrote that if two usability experts had a child, they would produce PowerShell! I will caveat that with —<strong> they would produce PowerShell and OBJECTS.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d01ee66232e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PowerShell Survival Guide Part 2]]></title>
            <link>https://medium.com/@byteslovesbits/powershell-survival-guide-part-2-c456baad1814?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c456baad1814</guid>
            <category><![CDATA[windows-10]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Sat, 22 Oct 2022 08:48:07 GMT</pubDate>
            <atom:updated>2022-10-23T10:55:15.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N60FopAo-tAGwzcg.jpg" /></figure><h3>Lots of Versions of PowerShell</h3><p>Windows ships with PowerShell 5.1 as standard. 5.1 is shit, so you’ll want to upgrade to the latest and greatest — version 7 — which is less shit.</p><p>Naturally, in the world of IT, we are consumed by bigger numbers. Bigger is better — generally speaking. Version 7.* is open-source and runs on MacOS and Linux. However, the MacOS and Linux versions are vastly inferior to the Windows versions and contain considerably less <strong>cmdlets</strong>.</p><h3>Cmdlet</h3><blockquote>A <strong>cmdlet</strong> — pronounced command-let — are commands on steroids! Cmdlets are user friendly and reduce our need to memorize.</blockquote><p>Cmdlets are a quantum-leap in command-line usability. Compared to PowerShell, the old way of doing things was frustrating and dare I say it — shit. If you are just starting out with command line interfaces — your journey will be very rewarding and with considerably less friction.</p><h3>Which Version Should I Use?</h3><p>Naturally, you will want the latest version, but remember — many features are not cross compatible and this will likely manifest in your programs breaking. However, if you <strong>design your programs to be fault-tolerant</strong>, which I will teach you over this series of articles, it is likely that the version number you choose should not make too much of a difference.</p><p>Grab the latest version for your operating system over at <a href="https://github.com/PowerShell/PowerShell">github</a>. For now, accept the defaults when you install PowerShell and don’t worry about anything else.</p><h3>Enough Already — Show Me the Power in PowerShell</h3><p>So Jane, Jeff, John or whoever comes over to you and says their program is acting weird. Usually it will be some Microsoft application but not always.</p><p>You head over to investigate or you remote onto their machine with your fancy pants remote desktop software.</p><p>Let’s now jump to the point where you have tried everything and this application is just being an absolute bastard and your only option left is to kill it off.</p><p>Your first instinct is to open <strong>task-manager</strong>, find the problematic application, right click the application and select <strong>end-task</strong>. This will work in most scenarios and is quicker and better practice than firing up PowerShell and typing some cmdlets. See Figure below. But what if this doesn’t kill off the application?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zilqY4fTC71PIYLS6UQpDw.gif" /><figcaption>Figure — Killing off an application with task-manager</figcaption></figure><h3>What if Task-Manager Doesn’t Kill off the Application?</h3><p>You could do a number of things — logoff, restart etc but this is an opportune moment to flex your PowerShell muscles.</p><p>Fire up PowerShell. In Windows, the quickest way to do this is to hit the Windows key, search for PowerShell and hit enter.</p><blockquote><strong>CRITICAL ADVICE. Don’t be an operating system snob.</strong> I’m writing this document on a MacBook Pro that connects to a Windows 11 Pro Machine that runs Windows Server 2022 and Kali Linux. I suggest that you setup a multi-operating system environment. If you limit yourself to one operating system, your usefulness to solve problems is reduced and you’ll likely be perceived as less professional.</blockquote><h3>Our First Mini Program</h3><p><strong>Problem:</strong> You want to find the two most memory consuming applications and kill them off. This is relatively easy to do in task-manager but imagine finding the first 20 applications and individually clicking each application and selecting end-task. Not fun! Let’s use PowerShell’s automation prowess to help us out.</p><p><strong>Solution:</strong> PowerShell. Often, real world machines run out of memory and you will have to free up some memory for the machine to become usable. See Figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PC2q_Z7yb0RrkJUDA0tGWw.gif" /><figcaption>Figure — Finding memory hogs and killing them off</figcaption></figure><p><strong>Discussion:</strong></p><p>In one line of code, you can automate x amount of tasks. Imagine if x = 100. It would be a bad day at the office if you had to manually search for and click a hundred different things.</p><p>PowerShell’s true power is its ability to process objects. Here, we get all the processes on our system using the cmdlet <strong>get-process.</strong> We then send all those processes to another cmdlet called <strong>sort-object</strong> that sorts those processes by memory consumed and in descending order. <strong>sort-object</strong> then passes those sorted processes to the cmdlet <strong>select-object </strong>which selects the first two processes. Finally, <strong>select-object </strong>passes those two memory hogging processes to the <strong>stop-process </strong>cmdlet which knows how to kill them off!</p><p>What is truly remarkable about his whole process — no pun — is the fact that we use cmdlets or commands that make intuitive sense and read almost like a sentence. You could say it like this.</p><h4>Get all processes and sort them in descending order of memory used. Then select the first two processes and kill them off.</h4><p>PowerShell takes the cryptic command lines of the past and rewrites the usability rulebook to be usable NOT confusing.</p><p>Stay with me for part 3 where we will look at PowerShell’s exceptional usability features.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c456baad1814" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PowerShell Survival Guide]]></title>
            <link>https://medium.com/@byteslovesbits/powershell-survival-guide-274fccd06379?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/274fccd06379</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Thu, 20 Oct 2022 17:20:52 GMT</pubDate>
            <atom:updated>2022-10-26T19:25:51.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>PowerShell Survival Guide Part 1</h3><blockquote>When it comes to learning PowerShell, you have endless pathways to choose from. What if I made huge claim — most of these pathways are a waste of time and not grounded in the reality of modern business!</blockquote><p>Would you be skeptical of my claim? If so, you are a critical thinker and my job for the rest of this series of articles is to convince YOU, through carefully crafted arguments, that my approach to learning PowerShell is a more effective pathway — grounded in the reality of modern business and none of the BULLSHIT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KSYc3OFK12jbZwh2.jpg" /></figure><h3>What is PowerShell</h3><p>So you just landed a job in IT and some of your coworkers have been saying PowerShell this, PowerShell that. Some of those coworkers rave about PowerShell, whilst others are less enthusiastic. Either way, you are curious about what PowerShell is and what it can do for you as a professional.</p><p>PowerShell is but one tool in a bottomless toolbag that modern IT professionals should use and master. At its core, PowerShell is an extremely powerful environment that helps us to get <strong>shit-done</strong>. When I say shit, I mean IT related stuff and by stuff, I mean solving business problems.</p><blockquote>Let’s face it — business-problems will be our bread and butter, whether you like it or not.</blockquote><p>Without getting too technical, at least for now, I can say this — PowerShell helps us to automate mundane and boring tasks that would otherwise occupy a significant portion of our day. By automating our tasks, we can focus on doing more interesting stuff, like learning about new technologies and helping our companies grow.</p><p>You could say that PowerShell is like a pet robot that we can work to death! PowerShell is our very own slave — albeit, without the immorality and suffering of a human slave. The key difference between PowerShell and a real slave is that PowerShell was designed and destined to perform repetitive tasks forever — <em>ad infinitum…</em></p><blockquote>PowerShell was designed and destined to perform repetitive tasks forever — <em>ad infinitum…</em></blockquote><p>Slavery is extreme language but I use it here to illustrate a key point. PowerShell has the potential to do most of our heavy lifting, without wane or compromise. Also, PowerShell, by virtue of its name, is as you would imagine, exceptionally powerful. Furthermore. PowerShell was designed for ease of use and has exceptional USABILITY.</p><blockquote>PowerShell’s usability is instrumental in its success. It is made by users for users…</blockquote><h3>PowerShell’s True Power Comes from Objects</h3><p>PowerShell’s real power derives from its ability to process everything as object(s).</p><p>Consider the opposite of PowerShell, such as a Linux shell, where nothing is an object. When nothing is an object, we have to write more code to get the same shit-done as what PowerShell can do in one line. In this respect, PowerShell is not only powerful, but incredibly economical with words. Not too dissimilar to my prose in this article — i hope. When we talk about PowerShell’s power, what we are really talking about is OBJECTS.</p><p>Stay with me for <a href="https://medium.com/@byteslovesbits/powershell-survival-guide-part-2-c456baad1814">part 2</a> where we solve real world problems that you will almost certainly come across in your new job. What most resources fail to mention is that these problems are typically done under pressure, whilst people watch over your shoulder. This is something those cool tutorials on YouTube always neglect to cover.</p><p>Is my claim starting to make sense?</p><p><strong>Remember</strong>. Clap and share. This shit is not easy to write and is 100x harder to edit. Please show your appreciation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274fccd06379" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PowerShell Exception Handling — Part 1.]]></title>
            <link>https://medium.com/@byteslovesbits/powershell-exception-handling-part-1-1e77e4c2e7d6?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e77e4c2e7d6</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[powershell]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Sun, 16 Oct 2022 13:23:11 GMT</pubDate>
            <atom:updated>2022-10-16T13:41:22.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>PowerShell Exception Handling — Part 1.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FaZVH9aHfVpvSesb4hOIQ.png" /></figure><blockquote>This article shows how we handle errors in PowerShell. We explore how <strong>Exception-Handling</strong> works to help improve the quality of ourcode.</blockquote><p>A computer program will either run as expected or it won&#39;t. When the program behaves <strong>unexpectedly</strong>, we need to prevent the program from terminating, so that the program continues to do useful stuff — such as keeping our computer networks running smoothly.</p><p>To prevent our programs from terminating unexpectedly, we use PowerShell’s exception-handling features. These features help to produce <strong>fault-tolerant-code</strong>.</p><h3>The Reality of Modern Code</h3><p>In a perfect world, every statement you write will run flawlessly — unfortunately, the world is imperfect and your code will break at some point! This hard truth is the norm, not the exception. No pun. Honest.</p><p><strong>How do we write perfect code?</strong> We can&#39;t, but we can write more fault-tolerant code by incorporating exception-handling techniques into our coding practices.</p><h3><strong>What is Exception Handling?</strong></h3><p>The Cambridge dictionary defines an exception as:</p><blockquote><strong>Something that does not behave in the expected way.</strong></blockquote><p>When our code runs normally, it behaves as expected. When it doesn’t run as expected, we say an exception has occurred. Exceptional code is erroneous code and erroneous code needs to be handled for the program to continue. Hence the term, <strong>error-handling</strong>.</p><blockquote>Error-handling is simple. When our code behaves unexpectedly, we handle that unexpected behaviour, so that our program can continue to do other stuff.</blockquote><p>Imagine a program with 1,000,000 lines of code. Further imagine the program behaves unexpectedly on line 2. If we don’t handle this unexpected behaviour at line 2, the program will terminate and the next 999,998 lines of code <strong>will not run!</strong> Imagine telling the person(s) who wrote those 998,998 lines of code that they wasted their time because they did not consider exception-handling! Fortunately, PowerShell has built-in exception-handling features that help us to produce more <strong>fault-tolerant-programs</strong>.</p><h3>Fault Tolerant Programs</h3><p>Fault-tolerant-programs run without interruption when one or more of their components fail. Advantages of fault-tolerance include high-availability and improved continuity of mission-critical applications. Improved continuity is one of the hallmarks of well designed software.</p><p>Fault-tolerance should be a considered factor of every software project! As software-consumers, errors are abhorrent. They cost us money and interrupt business processes. Let’s strive to write <strong>fault-tolerant programs…</strong></p><blockquote>The last thing we need as consumers of software, is yet another error stopping us from doing what we want.</blockquote><h3>Exception Handling Syntax</h3><p>PowerShell’s exception-handling syntax comprises of the try, catch, and finally blocks to handle <strong>terminating-errors.</strong></p><pre>try {&lt;statement list&gt;}</pre><pre>catch [[&lt;error type&gt;][&#39;,&#39; &lt;error type&gt;]*] {&lt;statement list&gt;}</pre><pre>finally {&lt;statement list&gt;}</pre><p>Terminating-errors<strong> </strong>stop statements from running. If we do not handle a terminating-error, PowerShell stops execution. When a terminating-error occurs, we say <strong>“an exception has been thrown”</strong> and we must handle that exception if we want to continue the expected flow of the program.</p><blockquote>Terminating errors throw exceptions. For the program to continue, we must handle those terminating-errors or exceptions.</blockquote><p>The code in the try block runs first. If the code in the try block throws an exception, an error-object is passed to the code in the catch block and the statements within the catch block are run. Hence the term, <strong>catching an exception</strong>. Code in the finally block will always be executed before control flow exits the entire construct.</p><p>try statements can include multiple catch blocks to catch or handle different types of thrown exceptions. So you could have.</p><pre>try {&lt;statement list&gt;}</pre><pre>catch [[&lt;error type&gt;][&#39;,&#39; &lt;error type&gt;]*] {&lt;statement list&gt;}</pre><pre>catch [[&lt;error type&gt;][&#39;,&#39; &lt;error type&gt;]*] {&lt;statement list&gt;}</pre><pre>catch [[&lt;error type&gt;][&#39;,&#39; &lt;error type&gt;]*] {&lt;statement list&gt;}</pre><pre>catch [[&lt;error type&gt;][&#39;,&#39; &lt;error type&gt;]*] {&lt;statement list&gt;}</pre><pre>finally {&lt;statement list&gt;}</pre><p>The finally statement list will always run, even if there are errors or not.</p><p>Head over to part2 where I demonstrate some production-coding examples involving try catch and finally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e77e4c2e7d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Modules — in 2 mins]]></title>
            <link>https://medium.com/@byteslovesbits/javascript-modules-in-2-mins-8048dc9690f0?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8048dc9690f0</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 11:37:03 GMT</pubDate>
            <atom:updated>2022-07-01T11:37:03.268Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Modules in 2 mins</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*0Pz5cAgsKxbjDGlrnqXePQ.jpeg" /></figure><blockquote><strong>JavaScript modules</strong> help us organize our code.</blockquote><h3>Complexity and Abstractions</h3><p>We are intimately familiar with the concept of complexity. Complex stuff hurts our brains, so we filter out the stuff we don’t need and focus on the stuff we need — this is called <strong>abstraction.</strong></p><blockquote>Abstractions look at things as a whole as opposed to the components that make up things.</blockquote><p>Look at your hand. It is an abstraction of many complicated bones, tendons and cells, but to you, it is just your hand. You know how to use your hand without thinking about the complex bio-mechanics of the hand.</p><p>Abstractions are all around us. Take the humble door handle. A door handle has many hidden components. Components have well defined purposes and interactions with other components. When all the components come together, we have a door handle — the door handle is the <strong>abstraction</strong>. All we think about when using a door handle is how our hand interacts with it. We don’t think about the components that make up the door handle.</p><p>Abstracting away complex components from everyday objects allows us to focus on <strong>function</strong> rather than form. In a world without abstractions, we would be driven to insanity by trying to understand everything — ad infinitum…</p><p>We may start at something like a laptop and decompose it into more granular things like motherboard and ram. We would further decompose motherboards into integrated circuits and decompose integrated circuits into sub-integrated circuits. We would then decompose sub-integrated circuits into basic electrical circuits and scores of decompositions later, we are staring atomic and sub-atomic particles in the face. Thus, without abstractions, long journeys down the rabbit hole would be unavoidable.</p><p>Take another example. A typical watch has hundreds of components. We don’t need to understand any of those components to understand time. The watch abstracts those details and presents them as a watch face — which we know how to read quickly. The true beauty of abstraction is how transformative it is. Abstractions transform the complex into the simple and intuitive.</p><blockquote>Abstractions transform the complex into the simple and intuitive.</blockquote><blockquote>Chrome has about 10 million lines of code. It abstracts this complexity from the user via a simple interface.</blockquote><h3>What are Modules?</h3><p>A module is a JavaScript <strong>file</strong> containing JavaScript code. ES6 modules are officially built into JavaScript.</p><p>Modules help to divide our programs into distinct chunks. Each chunk or module has a single responsibility. Modules with a single responsibility are easier to reason about and test. Also, they form a solid foundation for improving the software-architecture of your application.</p><p>Modules are deceptively easy. We export stuff from a file and then import that stuff.</p><h3>Named Exports/Imports</h3><p>To <strong>export</strong> something from a file — use a named export.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b298b1a6df4e455c74235bb13ecfbfa/href">https://medium.com/media/7b298b1a6df4e455c74235bb13ecfbfa/href</a></iframe><p>To <strong>import </strong>what you exported — use named imports within {}</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8291ec1d397b3551f40376334c263b31/href">https://medium.com/media/8291ec1d397b3551f40376334c263b31/href</a></iframe><p><strong>What if two modules export the same name?</strong></p><p>When we import accelerate from Ferrari.mjs and Tesla.mjs , we have two versions of accelerate . Naming collisions are prohibited!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a4047d68abc121b603514cb1b1d2998/href">https://medium.com/media/0a4047d68abc121b603514cb1b1d2998/href</a></iframe><p>To avoid naming collisions, <strong>rename</strong> your imports.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f19b24eb202a0efd07e48fcee4f6603/href">https://medium.com/media/9f19b24eb202a0efd07e48fcee4f6603/href</a></iframe><h3>Default Exports/Imports</h3><p>Export something as a default with <strong>default export</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/561d0275c903c32f18495c7c7d8bbf2e/href">https://medium.com/media/561d0275c903c32f18495c7c7d8bbf2e/href</a></iframe><p>Then <strong>import</strong> that default something as any name you want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1e5330293cef249674d17ec71fceba5/href">https://medium.com/media/a1e5330293cef249674d17ec71fceba5/href</a></iframe><h3>Mixing Named and Default Exports</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48e35090668bd87eb8b5fe7bbb1b9bca/href">https://medium.com/media/48e35090668bd87eb8b5fe7bbb1b9bca/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8048dc9690f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Walking the DOM]]></title>
            <link>https://medium.com/@byteslovesbits/walking-the-dom-36827fa8e01b?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/36827fa8e01b</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Thu, 12 May 2022 14:53:14 GMT</pubDate>
            <atom:updated>2022-05-12T14:53:14.468Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>When the browser downloads HTML, it builds a <strong>live-tree-data-structure</strong> called the Document Object Model (DOM). We manipulate the DOM to change the style, structure and content of a document — in real-time. <strong>In this article</strong>, I show you how to traverse the dom-tree.</blockquote><h3>The DOM Tree</h3><p>Everything in the DOM is a <strong>node</strong>. Figure 1. At the top of the <strong>dom-tree</strong> is the <strong>document-node, </strong>which is the <strong>parent-node</strong>. Nodes have children and children with the same parent-node are siblings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jz6Sf1dQ_uhtHU8w.png" /><figcaption>Figure 1 — The DOM is a <strong>live-tree-data-structure</strong>.</figcaption></figure><h3>Node Relationships</h3><p>Dom-nodes are related. We have parents, children and siblings. Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvQ5YJsL-XLnVbDhywO9pg.png" /><figcaption>Figure 2 — The relationships between nodes.</figcaption></figure><h3>The Root-Node</h3><p>The document-node is the <strong>root-node</strong>. It has no parent-node. Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBgAEOROMEecFUVgh8bqLw.png" /><figcaption>Figure 3 — The document-object is the ultimate root-node.</figcaption></figure><h3>Software Setup</h3><blockquote><strong>Zero setup</strong>. Use your favourite browser. Figure 4. 👍</blockquote><ol><li><strong>Type</strong> about:blank in Chrome’s address bar to get a basic html-page.</li><li>Right-click the document and select inspect to bring up Chrome’s developer tools.</li><li>Hit Escape to toggle the console.</li><li>Copy the code below Figure 4 into the ‘Element’s tab’.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*d4PuF-pgl2Lnc-hsEIhldA.gif" /><figcaption>Figure 4 — Copy the HTML below into Chrome’s developer tools.</figcaption></figure><pre>&lt;html&gt;</pre><pre>&lt;head&gt;</pre><pre>&lt;title&gt;Walking the DOM&lt;/title&gt;</pre><pre>&lt;style&gt;</pre><pre>.parent-div {</pre><pre>border: #e3fae3 solid 15px;</pre><pre>margin: 10px;</pre><pre>}</pre><pre>.child-div {</pre><pre>border: #cfe4ff solid 15px;</pre><pre>margin: 10px;</pre><pre>}</pre><pre>p {</pre><pre>border: #6f7681 solid 5px;</pre><pre>margin: 10px;</pre><pre>padding: 10px;</pre><pre>text-align: center;</pre><pre>font-size: xx-large;</pre><pre>color: #6f7681;</pre><pre>}</pre><pre>&lt;/style&gt;</pre><pre>&lt;/head&gt;</pre><pre>&lt;body&gt;</pre><pre>&lt;div class=&quot;parent-div&quot;&gt;</pre><pre>&lt;div class=&quot;child-div&quot;&gt;</pre><pre>&lt;p&gt;a&lt;/p&gt;</pre><pre>&lt;p&gt;b&lt;/p&gt;</pre><pre>&lt;p&gt;c&lt;/p&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><h3>Locating Dom Nodes</h3><p>We locate dom-nodes in three common ways. Figure 5.</p><ol><li>Selecting them in the document</li><li>Querying the DOM with document.querySelector(selectors)</li><li>$0</li></ol><blockquote>$0 returns the current selected element or JavaScript object.</blockquote><blockquote>document.querySelector(selectors) returns the first Element within the document that matches the specified selector, or group of selectors.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFvcytDUn0sY5TyeIYetDA.gif" /><figcaption>Figure 5 — Different ways to locate dom-nodes.</figcaption></figure><h3>Traversing the DOM</h3><p><strong>First</strong>, locate the dom-node and ask the dom-node:</p><p>Do you have a parent?</p><p>Do you have children?</p><p>Do you have siblings?</p><p>We ask these questions by accessing <strong>properties</strong> or executing<strong> methods </strong>on the dom-node. Some of these properties and methods include:</p><pre>childNodes</pre><pre>firstChild</pre><pre>lastChild</pre><pre>nextSibling</pre><pre>previousSibling</pre><pre>ParentNode</pre><pre>Methods</pre><pre>hasChildNodes()</pre><h3>Example</h3><p>Let’s ask a dom-node who is its parent is, who are its children, who is its first-child and finally who is its last child.</p><p><strong>First</strong>, select the dom-node. Figure 6.</p><pre>&lt;div class=&quot;child-div&quot;&gt;</pre><p>This &lt;div&gt; or element-node can be accessed through $0. Let’s use $0 for convenience. Figure 6.</p><p>Alternatively, access it programmatically with:</p><pre>let myElement = document.querySelector(&#39;.child-div&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsZHXSQ2ovCrSwtHUBJZdg.gif" /><figcaption>Figure 6 — Traversing the dom.</figcaption></figure><h3>Chaining Example</h3><p>We can also get grandparents by chaining. Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFalNdo-Hso2CHIsExMR8g.gif" /><figcaption>Figure 7 — Chaining in action.</figcaption></figure><h3>Summary</h3><p>Traversing the dom is not as complicated as many articles suggest. Method and property names are extremely intuitive. We mainly work with parents, children and siblings.</p><p>Head over to Chrome’s developer tools and experiment by accessing properties and methods on $0. Figure 8.</p><blockquote>Remember, $0 is a reference to the currently selected dom-node.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IHiNPxzPk-yKQX2gNrdNQ.gif" /><figcaption>Figure 8 — Helpful and intuitive code completion.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36827fa8e01b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous JavaScript]]></title>
            <link>https://medium.com/@byteslovesbits/asynchronous-javascript-906da20f37d8?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/906da20f37d8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Sat, 07 May 2022 09:27:28 GMT</pubDate>
            <atom:updated>2022-05-07T09:27:28.036Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s go back in time and look at the world’s first web-page. It was relatively dull text. Back then, it was all about sharing static-documents or text-content. If you were a web-developer, life was simple, life was good. However, as time passed, people demanded more from the web than mere static-content. They demanded a dynamic experience! — an experience where the client-server model of computing would make things more expressive and exciting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j5Mz0PqixBCHHUyZ" /><figcaption>Figure 1 — Tim Burners-Lee’s first ever website</figcaption></figure><p>Fast forward to the present day and for most people, the web-browser <strong>is the internet</strong>. The web-browser is a ubiquitous, all singing, all dancing window to the world. It is dynamic and exceptionally powerful. It represents decades of software development and refinement.</p><p>From the browser’s humble beginnings displaying text, we now use our web-browsers to play games, edit videos, track the economy, feed the cat, crash a drone, monitor our health and facetime people. The list is endless and we do all this ‘stuff’ asynchronously!</p><blockquote><strong><em>Asynchronous Definition:</em></strong><em> processes that operate independently.</em></blockquote><p>Being asynchronous is just a fancy way to say we can do multiple things at the same time. Think of watching your favourite movie. You don’t have to watch the video, then listen to the audio. We can watch and listen at the same time. In essence, you have video and audio processes that combine to produce a better experience.</p><h3>JavaScript — the Programming Language of the Web</h3><p>Of all the programming languages — it is JavaScript that has cemented its legacy as the programming language of the web. JavaScript has evolved from a relatively toy language to become an extremely powerful, expressive, multi-paradigm language that dominates the client-side. Also, it is making significant progress on the server-side through <strong>node.js</strong>. If you need one language to do most things, the argument for JavaScript is strong.</p><p>JavaScript is baked into all browsers through various engines such as Chrome’s V8 and Firefox’s SpiderMonkey. If you would like to quickly experiment with JavaScript, go to your browser’s developer tools where you will find a REPL (Read Evaluate Print Loop) within the console section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ap9rxC4Rs8GH9TDv.png" /><figcaption>Figure 2 — Experimenting with Chrome’s V8 Engines REPL in Chrome’s Developer Tools. Here, I access the DOM to change the documents title.</figcaption></figure><p>Despite JavaScript’s widespread acceptance as the programming language of the web, it may come as a shock that:</p><blockquote><em>JavaScript is not asynchronous!</em></blockquote><p>What? You are probably a little confused now. I too was confused. But don’t fear, I will explain how a <em>synchronous</em>, <em>blocking</em>, <em>single-threaded</em> language like JavaScript can magically become asynchronous.</p><h3>JavaScript is Synchronous</h3><p>Generally speaking, JavaScript will execute your code in a line by line fashion, but only after the environment hoists declarations to the top of their current scope. Figure 3 illustrates this concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gJ0cb-cJJkMamW9D.png" /><figcaption>Figure 3— Hoisting, moves declared functions to the top of the function’s current scope so that the function can be used before it is declared</figcaption></figure><blockquote><strong><em>Hoisting Definition:</em></strong><em> moving declared functions, variables and classes to the top of their current scope before execution.</em></blockquote><p>Hoisting is a relatively simple concept. However, to become better JavaScript programmers, we need to understand the inner workings of the environment that executes JavaScript. This is where the magic happens! This is how we <strong><em>tame the asynchronous beast!</em></strong></p><h3>The JavaScript Engine</h3><blockquote><strong><em>A JavaScript Engine</em></strong><em> is software that executes JavaScript code.</em></blockquote><p>The JavaScript Language is officially defined in the <a href="https://www.ecma-international.org/publications-and-standards/standards/ecma-262/">ecma-262 document</a>. This document or definition, serves to standardize the language. Standardizing the language is a fancy way of saying — we want users with different web-browsers to have the same experience when visiting the same page.</p><p>For the user experience to be the same, web-browsers must include a JavaScript engine that complies with the ecma-262 standard. Remember, JavaScript is executed through this engine.</p><p>JavaScript engines are commonly baked into web-browsers. For example, Chrome uses the V8 engine and Firefox uses the SpiderMonkey engine. JavaScript engines are not limited to web-browsers. <strong>Node.js</strong> is a back-end JavaScript runtime environment that runs on the V8 engine. We download node.js as an executable which contains everything we need to run JavaScript outside of the browser.</p><h3>Chrome V8 and the Call Stack</h3><p>Before diving into asynchronous concepts, let’s look at a visualization of how the browser executes code using the V8 JavaScript engine. V8 uses a data structure known as a call stack.</p><p>The call stack is simple. As a function is called, the function is added to the top of the stack, as a function returns, the function is removed from the top of the stack. We push onto a stack and pop off a stack. This is how synchronous JavaScript works. Figure 4.</p><p>We can observer this behaviour through the browser’s developer tools. Figure 5 shows this behaviour within Chrome’s developer tools. As we debug the code, we can see where in the call stack we are. Once we return from function a, a will be removed from the call stack — leaving just c and anonymous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s1l57C0xnxXho7yC.gif" /><figcaption>Figure 4— the JavaScript Call Stack</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*-yNWG0lKL-5rAlsw.png" /><figcaption>Figure 5 — V8 Call Stack in Chrome.</figcaption></figure><p>Now here is where it gets tricky! JavaScript as a language is single threaded. This means you cannot tell JavaScript to create multiple threads that run in parallel. In JavaScript land, functions can only be run one after the other. Just like in the call stack animation above. Having said that, JavaScript implementations such as V8 use multiple threads to do many things simultaneously.</p><p>V8 is multithreaded. This means that you can do other stuff in the background. For example, as you scroll down your favourite article, the page could be fetching data from an end-point that connects to a database, which then updates the page. If you have multiple CPU cores, each asynchronous thread of execution may be assigned to one of those cores. So, whilst the JavaScript language per se is not multi-threaded, the environment which executes JavaScript code is.</p><p>So the JavaScript environment executes JavaScript synchronously, on a single call stack.</p><p>So how does JavaScript do multiple things at once? How does a web-page that contains JavaScript, retrieve data from a server and perform long running calculations — all whilst dynamically updating the page and keeping the page interactive.</p><p>The answer is with the help of the web-browser. You see, whilst JavaScript is single threaded, the browser is capable of doing many things at the same time and one of those things is to give the illusion that JavaScript is asynchronous. At the most fundamental of levels, this illusion is created through the computer programming concept of a <strong><em>‘callback’</em></strong>.</p><h3>Callbacks</h3><p>A callback is a function that we pass to another function as an argument. That other function will then invoke our passed in function. Callbacks are critical parts of asynchronous JavaScript! Although they are a relatively simple concept, they are central for more advanced asynchronous JavaScript concepts, such as <strong><em>promises</em></strong> and <strong><em>async await</em></strong>. Callbacks come in two flavours, synchronous and asynchronous. Let’s start with synchronous callbacks.</p><p>Figure 6 shows a very basic callback. Line 1 declares a callback function. This is the function that gets ‘called back’.</p><p>Line 5 is the function that receives the callback function. A function like this, that receives another function as an argument or returns a function is known as a <strong><em>higher order function</em></strong>.</p><p>One line 9, we pass the callback function into the higher order function named doSomething, which then invokes the callback function on line 6. Execution jumps to line 2, where the callback does a console.log. Note also how we can pass anonymous functions as callbacks to the higher order functions. Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*PccdirQPgGBCadMI.png" /><figcaption>Figure 6 — synchronous callbacks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*arOAdAwrKhZsArUS.png" /><figcaption>Figure 7 — passing an anonymous arrow function as a callback function</figcaption></figure><h3>Asynchronous Callbacks</h3><p>Synchronous callbacks are useful but to do more powerful things, we need a sprinkle of asynchronicity. We get some of this asynchonicity with the help of the web-browser, more specifically, the web-browser’s APIs.</p><p>The browser supplies web-apis that extend the JavaScript language so that the language can do useful things like asynchronous operations. Figure 8. There are many powerful web-apis, such as the GeoLocation api which can find a user’s gps coordinates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rC0bC6wRVPVDBseZ.png" /><figcaption>Figure 8 — extending the core language to make it more powerful</figcaption></figure><h3>Setimeout</h3><p>Finally, we get to do some asynchronous programming. Open up chrome and type about:blank into the address bar. This will give you a blank page. From within the console tab of the developer tools, type window followed by enter. Figure 9. Expand the right chevron next to the word window within the console and scroll down until you reach settimeout. Figure 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1sWtXNT3LnDtyHwb.png" /><figcaption>Figure 9 — accessing the JavaScript global object from Chrome’s developer tools</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IXL-wH0wn5UCo8me.png" /><figcaption>Figure 10 — settimeout is a global function</figcaption></figure><p>The <strong>setTimeout()</strong> method is part of the browsers global object. <strong>setTimeout() </strong>sets a timer which executes code once the timer expires. <strong>setTimeout()</strong> is part of a web-api that creates the illusion that JavaScript is asynchronous. We will use the <strong>setTimeout()</strong> method next to do some asynchronous programming.</p><p>Within the same about:blank page, type the contents of Figure 11 into the console. Figure 12. Hit enter and after three seconds the blank page will display ‘Asynchonous JavaScript’. Congratulations you are now an asynchronous programmer!</p><p>Setimeout is simple. It calls myfunction after three 3000 milliseconds, which changes the innerHTML of the document’s body to display ‘Asynchonous JavaScript’. Bonus points if you spotted the typos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tq1j0IyxxkK1Oa1i.png" /><figcaption>Figure 11 — incorrectly spelling asynchronous</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kcOctUPArrG9_SFO.png" /><figcaption>Figure 12 — executing an asynchronous function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OLGdZnEBcZ5uA4Dr.png" /><figcaption>Figure 13 — web apis in action. setimeout asynchronously updates the DOM after three seconds</figcaption></figure><p>To recap, we use the help of the browser to give the illusion that JavaScript is asynchronous. <strong>setTimeout()</strong>is part of the browser’s global object and it allows us to give the illusion that synchronous JavaScript code is asynchronous. Figure 14.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/0*irnSN05FF6_TFZ9U.png" /><figcaption>Figure 14 — setimeout is supplied by the browser</figcaption></figure><h3>Blocking Code</h3><p>Let’s say we have a fancy pants web-page with a single button. We never know when a user will click that button. It could be now or it could be in several hours. We just don’t know. Because JavaScript is synchronous, this means the page just sits there waiting for the button to be clicked. It hangs. Unable to proceed to the next line of code — until the button is clicked. This is what is known as <strong>blocking code</strong>. Everything is blocked until the button has been pressed.</p><blockquote><em>Blocking code: Code cannot execute until some other code finishes</em></blockquote><p>To observer similar blocking behaviour, type <strong>alert()</strong> into the console. Figure 15— the <strong>alert()</strong>method is a synchronous browser method and it completely blocks everything until the dialogue box is dismissed by the user. From a user’s perspective, blocking code is horrendous and is usually a worst case scenario. The user cannot do anything with the page. It is blocked! They cannot scroll, zoom in, click a button, send a message, click like. The page is effectively dead!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NFLSGAVhVqHSI5Af.png" /><figcaption>Figure 15 — blocking code using the alert() method</figcaption></figure><p>So how does the browser prevent blocking code? In other words, how does it improve JavaScript’s synchronous model of execution? The browser provides us with asynchronous methods as part of its web-apis. We use these asynchronous methods to add <strong>event listeners</strong> to buttons or elements. The event listener waits asynchronously until the button is clicked. It then executes some code in response to the click. This way, the web page is free to do other useful stuff. There are many types of event listeners, such as events that fire when the mouse is clicked or the page loads.</p><p>Let’s look at an example of an event listener. Enter the code from Figure 16 into your web-browser’s console, followed by enter. Now click anywhere inside the white document to the left of the console. Observe how the document colour changes from white to red. Figure 17. This my friends, is asynchronous JavaScript in action. What we are doing is listening for a click event on the document’s body and when that event happens we change the document’s CSS background color property to red. Also, note how the browser asynchronously changed the body style to <strong>&lt;body style=&quot;background-color: red;&quot;&gt;&lt;/body&gt;</strong>.Figure 5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-D2lXfd96BNodanS.png" /><figcaption>Figure 16 — adding an event listener to the dom body object</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CvbOmPCzl2n_JEg8.png" /><figcaption>Figure 17 — the event fires and the body changes colour</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5r-qnkMq3zeNYXUi.png" /><figcaption>Figure 18 — the browser asynchronously updating the DOM</figcaption></figure><h3>The Event Loop</h3><p>We now arrive at what is perhaps the most critical aspect of understanding asynchronous JavaScript — the event loop. Figure 19.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1t2k724c_PxQs2fw.png" /><figcaption>Figure 19 — The event loop.</figcaption></figure><p>One way to understand the event loop is to see how Chrome’s V8 engine works. Copy the code from Figure 20 into Chrome’s developer tools console and press Enter. This will take us to a debugging environment where we can analyse V8’s order of execution. Figure 21.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*k15k1HV2DZ0iPoei.png" /><figcaption>Figure 20 — asynchronous execution order</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yU2A4K8mU_vsslah.png" /><figcaption>Figure 21 — enter the code into the console and press enter to open a debugging environment.</figcaption></figure><h3>Order of Operations</h3><p>The debugging environment from Figure 21 provides us with a high level view of V8’s behaviour.</p><p>First, the <strong>main()</strong> or <strong>anonymous()</strong>function is pushed onto the stack.</p><p>V8 will then execute code synchronously until it reaches line 6.</p><p>On line 6, the browser turns synchronous JavaScript into asynchronous JavaScript with the help of the global web-api function named <strong>setimeout.</strong></p><p>The browser will then set a timer for 1000 ms and once that 1000 ms has elapsed, <strong>it will execute the code within the function that is passed to to </strong><strong>setimeout</strong>. In this case, the function passed into <strong>setimeout</strong> is an anonymous arrow function. In the meantime, V8 will proceed synchronously. It will execute <strong>c()</strong>as the <strong>setimeout </strong>function counts down from 1000 ms. This process is best illustrated using a GIF. Figure 22. Pay attention to the Call Stack area of the debugging window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6kv0qXeKCjaYFIhp.gif" /><figcaption>Figure 22 — analysing V8’s asynchronous behaviour</figcaption></figure><p>To further illustrate this concept, take a look at the GIF in Figure 23. The GIF asynchronously updates the DOM using a similar method to <strong>setimeout</strong> — named <strong>setinterval. </strong>Think of <strong>setinterval</strong>as calling <strong>setimeout</strong>over and over — <strong>Ad infinitum. </strong>Every second, the DOM is asynchronously updated to change the bodies background color to a random colour from within the colors array. Also, the page is non-blocking, meaning we can interact with it! <strong>In essence, the browser gives the illusion that JavaScript is no longer a blocking, single threaded language. </strong>As <strong>setinterval</strong> counts down, the page is free to do other asynchronous stuff, such as fetching data from a server.</p><blockquote><em>The browser gives the illusion that synchronous, blocking, single threaded JavaScript is asynchronous JavaScript through the use of web-apis and the event model.</em></blockquote><blockquote><strong><em>setinterval</em></strong><em> and </em><strong><em>setimeout</em></strong><em> are asynchronous functions that are part of web-apis that are implemented by the browser vendor.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zamRHuzS44IkWlEh.gif" /><figcaption>Figure 23 — asynchronously updating the DOM every second</figcaption></figure><p>An interesting point about <strong>setimeout </strong>and <strong>setinterval</strong> is that these functions are not implemented by V8. If you were to grab the source code for V8 and search for <strong>setimeout</strong>, you would not find it. It is the responsibly of the various browser vendors such as Chrome and Firefox to implement these functions according to the HTML standard. Details of the event loop can are found in section <a href="https://html.spec.whatwg.org/multipage/webappapis.html#event-loops">8.1.6</a> of the HTML standard. Here you will also find detailed information on web-apis.</p><blockquote><em>For details how browser vendors implement the event loop, head over to section </em><a href="https://html.spec.whatwg.org/multipage/webappapis.html#event-loops"><em>8.1.6</em></a><em> of the HTML standard.</em></blockquote><blockquote><em>For details how browser vendors implement web-apis, head over the section </em><a href="https://html.spec.whatwg.org/multipage/webappapis.html#webappapis"><em>8</em></a><em> of the HTML standard.</em></blockquote><h3>Pulling Data from Servers</h3><p>Let’s begin by solving a <strong>real world problem</strong> using asynchronous JavaScript.</p><p>One problem that many developers face is pulling data from a server. Let’s use an extreme example to illustrate a major problem with using synchronous JavaScript to get data.</p><p>Imagine you are using your all-singing, all-dancing web-app from within the country Yemen. Yemen has an average internet speed of less than 1mbps according to my superficial critical analysis. Now, further imagine that your web-app needs to download a relatively small data-set of approximately 30MB. Plugging these numbers into an online calculator, it would take 240 seconds for that relatively small data-set to download. Figure 24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*y3kvoBSCCPKqDM_0.png" /><figcaption>Figure 24 — Download time for slow internet.</figcaption></figure><p>This is the Achilles heel of synchronous JavaScript. The user has no option but to wait 240 seconds before doing anything else. The web-app is completely blocking and non interactive during the download. This is a common example of an <strong>awful user experience</strong> and should be avoided at all costs!</p><p>240 seconds seems like an extreme example, but many usability studies show that mere seconds without an interactive experience causes users to go elsewhere. Remember, every second is critical to the success of your application. Time is not just about performance — time is also critical for a great user experience.</p><blockquote><strong><em>Remember </em></strong><em>— make your apps responsive. Do not frustrate your users and never make them wait!</em></blockquote><p>Think about this. How many times have you got frustrated with those apps that freeze while the page renders? I would imagine such experiences are deeply engrained into your lives at this point, given the sheer number of blocking sites that continue to plague the internet with awful user experiences.</p><p>Unfortunately, these blocking sites are the norm rather than the exception. To reduce the likelihood of producing a blocking site, we can make use of the Fetch web-api.</p><h3>Asynchronously Fetching Data with the Fetch API</h3><p>The fetch api fetches resources<strong> </strong>from the web. When a HTTP client such as a web-browser makes a HTTP request — the target of that request is known as a <strong>“resource”</strong>.</p><p>We get or modify resources on the web using a URI or uniform resource identifier. This URI, which you will typically see as the address in your web browser, identifies logical or physical resources.</p><p>Let’s look at fetch in action. We will use fetch to fetch posts from a remote server that is setup to respond to HTTP requests.</p><p>Open up Chrome and type about:blank into the address bar to get a minimal html page. Figure 25. Copy the code from Figure 25 into the console of the developer tools and hit enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JBTH9Vj9MepHjjv0.png" /><figcaption>Figure 25 — a basic get request using fetch</figcaption></figure><p><strong>fetch() </strong>will then make a request to <a href="http://jsonplaceholder.typicode.com/posts">http://jsonplaceholder.typicode.com/posts</a> which <strong>returns a promise.</strong> If the request completes, the promise is fulfilled with the Response object. If the request fails the promise is rejected. In this instance, we can see that the promise was fulfilled and returned an array of objects representing unique posts. Figure 26.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RWSjh-ccZTwIaAK3.png" /><figcaption>Figure 26 — Asynchronously fetching data using the fetch api</figcaption></figure><p>If you open up the network tab from within the developer tools you can gather rich information about the request and response objects. Figure 27.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bzC_GBCJY9E1MWTS.png" /><figcaption>Figure 27 — Accessing the HTTP information from a GET request.</figcaption></figure><p><strong>Congratulations.</strong> You have made your first asynchronous request for a resource on the internet.</p><h4>Show your support by sharing far and wide. Happy programming!!!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906da20f37d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The DOM — Simplified…]]></title>
            <link>https://towardsdev.com/the-dom-simplified-11f4820292b4?source=rss-97f5b7148e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/11f4820292b4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Marc Kirk]]></dc:creator>
            <pubDate>Thu, 05 May 2022 10:53:40 GMT</pubDate>
            <atom:updated>2022-12-30T09:08:48.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>The DOM Simplified</h3><blockquote><em>Ponder the idea of life without the browser! Awful right? Fortunately, we have browsers and they give us the gift of life — a </em><strong><em>window</em></strong><em> into our chaotic but wonderful world. </em><strong><em>This article</em></strong><em> explores the </em><strong><em>DOM </em></strong><em>with Chrome. Let’s begin…</em></blockquote><h3>Learning Objectives</h3><ul><li>Create, Read, Update and Delete <strong>HTML</strong> <strong>elements, attributes </strong>and<strong> CSS styles </strong>using the DOM.</li><li>Attach <strong>event-handlers</strong> to objects in the DOM</li><li>Master <strong>Chrome’s Developer Tools.</strong></li></ul><h3>What is the DOM?</h3><p>When the browser downloads HTML, it builds a <strong>live-data-structure</strong> called the Document Object Model (DOM). We manipulate the DOM to change the <strong>style</strong>, <strong>structure</strong> and <strong>content</strong> of a document — in real-time. Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3KJfsYXnotMazW-m9-1nQ.png" /><figcaption>Figure 1 — The Document Object Model (DOM).</figcaption></figure><p>When we change the DOM, we <strong>only change</strong> a representation of the HTML and not the source-code. This representation is known as the <strong>dom-tree. </strong>The browser-window’s document-object instantly shows changes to the dom-tree. Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BDZgn_m4-Q4GtxHtS0zOQ.png" /><figcaption>Figure 2 — The DOM represents HTML through a live-tree-data-structure.</figcaption></figure><h3>The DOM Tree</h3><p>Everything in the DOM is a <strong>node</strong>. At the top of the dom-tree is the <strong>document-node, </strong>which is the <strong>parent-node</strong> of all the nodes that sit below it. Nodes have children and children with the same parent-node are siblings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2OhV5hQQyblgGydvGeugA.png" /><figcaption>Figure 3 — The DOM is a tree-data-structure which can be changed in real-time.</figcaption></figure><h3>Where is the DOM Located?</h3><p>The DOM is part of a larger architecture known as the Browser Object Model (BOM). Figure 4. The BOM exposes powerful-objects to do things like get the user’s location or fetch data from a server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3brmXx6GThBqdh-BkDkAQ.png" /><figcaption>Figure 4 — The DOM is part of the BOM. Terminology!</figcaption></figure><p>For tabbed browsers, each tab is a <strong>window-object</strong> and that window-object contains the <strong>document-object</strong>. We use the DOM to manipulate the document-object to update the page. Figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnAb9hB6oytALhfOGUmXpQ.png" /><figcaption>Figure 5 — We update the document-object or page with the DOM</figcaption></figure><h3>How Do I Change the DOM?</h3><p>To change a document’s style, structure<strong> </strong>or content, we use <strong>dom-methods </strong>on the document-object. Note! — dom-nodes are <strong>objects</strong> and objects have methods and properties that we change with JavaScript. Figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YT5u4NoOiezMqHyYfC9NQ.png" /><figcaption>Figure 6— We change a dom-object using dom-methods and properties.</figcaption></figure><h3>CRUD Example</h3><p>Let’s use <strong>dom-methods </strong>to:</p><ul><li>Create an element-node.</li><li>Update the element-node’s innerText property to ‘Hello World’.</li><li>Append the element-node to an existing element.</li><li>Delete the element-node</li></ul><p><strong>First</strong>, type about:blank in Chrome’s address bar to get a basic html-page and then right-click the document and select inspect to bring up developer tools. Hit escape to bring up the console if not visible. Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AthVlYqjWn7LAAvrFIHaUg.gif" /><figcaption>Figure 7— Chrome’s developer tools on the <strong>about:blank</strong> page.</figcaption></figure><ol><li>We access <strong>dom-methods</strong> through window.document which returns a reference to the document contained in the window.</li><li>Let’s create a &lt;p&gt; element-node with let paragraph = window.document.createElement(&#39;p&#39;). Figure 8.</li><li>Let’s change the &lt;p&gt; element-node’s innerText property to ‘Hello World with paragraph.innerText = &#39;Hello World&#39;</li><li>We can now append the &lt;p&gt; element-node to the &lt;body&gt; element-node with window.document.body.appendChild(paragraph). Note how the DOM updates instantly! The DOM is a <strong>live-tree-data-structure. </strong>Also, observe how the HTML updates within the <strong>‘elements tab’</strong>.</li><li>Finally, we remove the &lt;p&gt; element-node from the &lt;body&gt; element-node with window.document.body.removeChild(paragraph).</li></ol><p>Congratulations, you interacted with the DOM using <strong>dom-methods</strong> and <strong>properties</strong>. How easy was that?👍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBnJWQXlmFqobmsuUcneCw.gif" /><figcaption>Figure 8 — Basic CRUD DOM interaction.</figcaption></figure><h3>Event Listeners</h3><p>Finally, let’s add a <strong>‘click’ event-listener</strong> to the &lt;body&gt; element-node to change the body’s background to a random colour when the user clicks within the document. Figure 9.</p><pre>document.body.addEventListener(‘click’,()=&gt;{document.body.bgColor= Math.floor(Math.random()*16777215).toString(16)})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9Juu0P6MU64hzzdQzsaWA.gif" /><figcaption>Figure 9 — adding event listeners to the DOM.</figcaption></figure><p>That wraps up our brief exploration of the DOM. If you would like a more in-depth explanation of the DOM, see <a href="https://medium.com/@byteslovesbits/the-document-object-model-explained-part-1-c672959d2e6">The Document Object Model — Explained — Part 1.</a></p><p><strong>Now go smash that clap button!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11f4820292b4" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/the-dom-simplified-11f4820292b4">The DOM — Simplified…</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>