<?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 Kris Mason on Medium]]></title>
        <description><![CDATA[Stories by Kris Mason on Medium]]></description>
        <link>https://medium.com/@masonk000?source=rss-9e46da7111a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*H8QpiL6yXxFWvCxsekgnJg.png</url>
            <title>Stories by Kris Mason on Medium</title>
            <link>https://medium.com/@masonk000?source=rss-9e46da7111a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:44:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@masonk000/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[Introduction to WebRTC]]></title>
            <link>https://levelup.gitconnected.com/introduction-to-webrtc-5310fae89085?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5310fae89085</guid>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[peer-to-peer]]></category>
            <category><![CDATA[video-chat]]></category>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 20:07:12 GMT</pubDate>
            <atom:updated>2020-07-25T23:16:51.567Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with open-source real time communications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWwS_KrTXtmMadzkKiz1Lg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cwmonty?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chris Montgomery</a> on <a href="https://unsplash.com/s/photos/video-call?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you haven’t heard, WebRTC is <em>the </em>way to go for getting and sharing user’s video, audio, and other data in real time. Standing for <strong>Web Real Time Communication</strong>, it is the first of it’s kind — with JavaScript APIs for getting user’s media, creating peer-to-peer connections, and opening data channels right in the browser. Before the release of WebRTC in 2011, it required several developers and a lot of C# to accomplish these tasks.</p><p>Now, nearly 10 years later, WebRTC is the standard for web and mobile media sharing. Standardized by the World Wide Web Consortium (W3C) and the Internet Engineering Task Force (IETF), it has native support in HTML5, and is open-source and totally free. All this means that you can get started using it today without installing any plugins or packages.</p><p>In this post, I will walk you through the APIs that enable WebRTC to do all this work, and provide some simple code snippets to get you familiar with the datatypes and how to get started using them.</p><p>Note: there is a lot going on with WebRTC, especially with the peer connections and data channels. I will provide links throughout to learn more about these tools, their contexts, and some of the configurations needed to use them.</p><h4>The Three WebRTC APIs</h4><p>WebRTC makes use of three JavaScript APIs:</p><ol><li>MediaStream aka getUserMedia — allows developers access to user’s media streams: webcam, microphone, and screen (with the user’s permission, of course)</li><li>RTCPeerConnection — enables audio and video “calling” between users via peer-to-peer connections</li><li>RTCDataChannel — uses the peer-to-peer connection to enable real time sharing of any other generic data between users</li></ol><h4>MediaStream</h4><p>The MediaStream is at the heart of the video/audio/screen sharing capabilities of WebRTC. It is incredibly easy to get started using this. Because this API is already available in the browser, you just need to make a call to getUserMedia:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6cea2b325c5c500684abc6ca5f4c44b/href">https://medium.com/media/d6cea2b325c5c500684abc6ca5f4c44b/href</a></iframe><p>As you can see, it is on the global navigator object, as a method on mediaDevices. Pass in a few arguments to get the particular media you want — here we are getting both video and audio from the user, without any constraints on the video or audio size, frame rate, aspect ratio, etc. Read more about <a href="https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API/Constraints">user media constraints on MDN</a>.</p><p>getUserMedia returns a promise with that user’s media stream, which is an object that looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb7656b316d5ad8b725c615800779baa/href">https://medium.com/media/fb7656b316d5ad8b725c615800779baa/href</a></iframe><p>In the prototype, you see that this stream has access to a bunch of handy methods, like getAudioTracks and getVideoTracks that can be used on our stream to further handle and potentially manipulate the media (see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a> for ideas on what you can do with the audio track).</p><p>Once we have access to this media stream, we can also display it through the &lt;video&gt; tag in our HTML. However you go about saving the returned stream in your code, just reference that location in the ref attribute: <br>&lt;video ref={usersSavedMediaStream} /&gt;.</p><p>Learn more about <a href="https://flaviocopes.com/getusermedia/">using the </a><a href="https://flaviocopes.com/getusermedia/">MediaStream and </a><a href="https://flaviocopes.com/getusermedia/">getUserMedia at Flavio Copes</a>.</p><h4>RTCPeerConnection</h4><p>Ok, so we have the user’s media but now how do we share it? Enter the peer connection. RTCPeerConnection represents a connection between the local user’s computer and remote peer user’s computer, with methods to connect, maintain, and close the connection. You can make the peer connection by creating a new instance of RTCPeerConnection and passing in your configurations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11b0f277e5426064948838616ca1dbbf/href">https://medium.com/media/11b0f277e5426064948838616ca1dbbf/href</a></iframe><p>The configurations can be many, but the only absolutely necessary one is the iceServers, which will hold an array of URL objects containing information on the STUN and TURN servers used during the process of finding the ICE candidates. Wow, that was a whole mouthful! On a very basic level, the ICE candidate is the information about the network exchanged between peers. While making the peer-to-peer connection, the two remote computers agree on the best connection between them. Read more about <a href="https://temasys.io/webrtc-ice-sorcery/">ICE candidates and STUN/TURN servers in this article by Sherwin Sim at Temasys</a>.</p><p>Now, while the API will allow you to make these peer connections, you will also need to use some kind of <em>signaling</em> to facilitate the peer-to-peer connection via a server. WebRTC doesn’t include an API for this, however there are a lot of options out there. I won’t go into this aspect of making the connection between peers, but I can recommend <a href="https://socket.io/">Socket.IO</a> as a Node.js based web socket option and you can learn more about <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling">signaling here on MDN</a>.</p><p>You might be thinking that this is pretty complex sounding — and you’re right. Since the initial release of WebRTC, there have been many libraries developed to obscure some of this complexity and make the peer-to-peer real time connections a little easier. <a href="https://github.com/feross/simple-peer">Simple-Peer</a> is a well known, open-source library for this, and the maker also has a nice library for signaling, called <a href="https://github.com/t-mullen/simple-signal">Simple-Signal</a> (which used <a href="https://socket.io/">Socket.IO</a>). In addition, you can check out this <a href="https://github.com/openrtc-io/awesome-webrtc">collection of WebRTC modules and resources</a>.</p><h4>RTCDataChannel</h4><p>The last API in WebRTC is one that lets developers open up a channel between two peers, through which we can send and receive an other data, such as text for a real time chat, or even file transfer of any files from one computer to another, like torrent-based file sharing. This is very similar to web sockets, introduced through the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSocket API</a> and is included in the features of Socket.IO.</p><p>To get started, you need a peer connection opened via RTCPeerConnection (or a library that handles this for you). Once you have that connection, you can call createDataChannel on the local peer and ondatachannel on the remote peer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb66820c5a203e831f321c45335591f3/href">https://medium.com/media/eb66820c5a203e831f321c45335591f3/href</a></iframe><h4>Conclusion</h4><p>This has been a high-level overview of the features available to you through WebRTC. Getting started working with user’s media is fairly easy with getUserMedia, while the complexity quickly ramps up in establishing peer-to-peer connections and data channels between users. You will need to use a third party API for handling server signaling (like <a href="https://socket.io/">Socket.IO</a>), and you may choose to use another library to help navigate the complexity of RTCPeerConnection and RTCDataChannel, like <a href="https://github.com/feross/simple-peer">Simple-Peer</a>.</p><p>While this set of powerful APIs can take a little time to get started using, it is an excellent, well-documented, immediately available and free way to bring real time video and audio communication, file sharing, and any other peer-to-peer remote exchange into your application.</p><p>For more in-depth tutorial on WebRTC, check out these two resources:</p><ol><li><a href="https://www.tutorialspoint.com/webrtc/webrtc_quick_guide.htm">WebRTC “Quick Guide” from Tutorials Point</a></li><li><a href="https://www.html5rocks.com/en/tutorials/webrtc/basics/">Getting Started with WebRTC from HTML5 Rocks</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5310fae89085" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/introduction-to-webrtc-5310fae89085">Introduction to WebRTC</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using SVGs with Tailwind CSS]]></title>
            <link>https://medium.com/swlh/using-svgs-with-tailwind-css-84e9e3526b63?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/84e9e3526b63</guid>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Sun, 19 Jul 2020 23:10:16 GMT</pubDate>
            <atom:updated>2020-07-20T00:13:10.355Z</atom:updated>
            <content:encoded><![CDATA[<h3>Styling SVGs with Tailwind</h3><h4>An introduction to SVGs, Tailwind CSS, and using them together</h4><p>You may be using Tailwind to style your project or are curious about how to integrate SVGs into your application. Whatever brings you here today, this article will give you a brief introduction to both SVGs and Tailwind CSS — one rather old web-based technology and one very young — and then jump into how to handle SVGs with Tailwind.</p><h4>What is SVG?</h4><p>SVG stands for <strong>Scalable Vector Graphics</strong> and is an XML-based vector image format developed by the World Wide Web Consortium (WC3). Around since 1999, SVGs are supported by all major modern web browsers. Being XML-based means SVGs can be created and edited with any text-editor and many image editing softwares.</p><p>The SVG is an image option that is generally more accessible that standard images, like .jpgs and .pngs, due to its infinite scalability and smaller file sizes, especially for larger graphics. The cool thing about SVG is that most vector editing software can also export into SVG, like Adobe Illustrator or Sketch. There are also many free online SVG editors and generators. In addition to be used for general graphics, the SVG is also commonly used for icons, animations, interactive charts and graphs, and other dynamic graphics in the browser.</p><p>SVG code runs the gambit from extremely simple to utterly complex, depending on the type of image. Here is an example of a simple SVG tag that creates a circle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c560cae7e7b912104bde686281a2b9c1/href">https://medium.com/media/c560cae7e7b912104bde686281a2b9c1/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fmasonkristopher%2Fembed%2Fpreview%2FRwrqXyM%3Fheight%3D600%26slug-hash%3DRwrqXyM%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fmasonkristopher%2Fpen%2FRwrqXyM&amp;image=https%3A%2F%2Fassets.codepen.io%2F4802041%2Finternal%2Fscreenshots%2Fpens%2FRwrqXyM.default.png%3Fformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D1%26amp%3Bversion%3D1595199934%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab7f607ebc48f091e3ecc9b45d0190e7/href">https://medium.com/media/ab7f607ebc48f091e3ecc9b45d0190e7/href</a></iframe><p>You can see that it does not take much code at all to make a circle. Here our code uses the &lt;circle&gt; tag, however there are several tags that can be used to add shapes and lines to an SVG:</p><ul><li>Rectangle &lt;rect&gt;</li><li>Circle &lt;circle&gt;</li><li>Ellipse &lt;ellipse&gt;</li><li>Line &lt;line&gt;</li><li>Polyline &lt;polyline&gt;</li><li>Polygon &lt;polygon&gt;</li><li>Path &lt;path&gt;</li></ul><h4>What is Tailwind CSS?</h4><p>Tailwind is an unopinionated and customizable CSS framework that as of my writing in July 2020 is just under a year old. It differentiates itself from popular CSS frameworks like Bootstrap by being focused on utilities. Rather than writing CSS in your style sheets, when you work with Tailwind, you write in classes directly in the HTML. The developers of Tailwind argue that because you can adjust nearly every detail in-line in the HTML, you can develop faster.</p><p>We can compare a simple button in between Boostrap and Tailwind:</p><p><strong>Bootstrap</strong></p><pre>&lt;button type=&quot;button&quot; class=&quot;btn btn-primary&quot;&gt;Bootstrap Button&lt;/button&gt;</pre><p><strong>Tailwind</strong></p><pre>&lt;button class=&quot;bg-green-500 hover:bg-green-700 text-white font-bold py-1 px-2 rounded&quot;&gt;Tailwind Button&lt;/button&gt;</pre><p>The trade-off is, of course, more in-line code for your button. But you can see here that the Tailwind button is more <em>quickly customizable</em> than the default Bootstrap button.</p><h4>Styling SVGs in Tailwind</h4><p>So the main thing about using Tailwind to style you SVG is the utility-first approach — remembering that much of the customization is happening in the class attribute of any element’s tag. This example is using a &lt;path&gt; tag, which is common for icons:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30987a785659e6094c6491414a24c1bb/href">https://medium.com/media/30987a785659e6094c6491414a24c1bb/href</a></iframe><p>If you remember from the circle example above, we set the height and width of our (infinitely-scalable) SVG via those attributes in the &lt;svg&gt; tag. Here we ditch those attributes, and use the built-in sizes in Tailwind: w-5 h-5 sets both height and witdh to 5 pixels.</p><p>We can adjust three other aspects of the SVG with Tailwind utilities: <a href="https://tailwindcss.com/docs/fill">fill color</a>, <a href="https://tailwindcss.com/docs/stroke">stroke color</a>, and <a href="https://tailwindcss.com/docs/stroke-width">stroke width</a>. In this example, the fill is set to the current text color with fill-current.</p><h4>What is the viewBox?</h4><p>You may have noticed that the viewBox attribute is not the same dimensions as the width and height mentioned above. <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox#:~:text=The%20viewBox%20attribute%20defines%20the,%2Dy%20%2C%20width%20and%20height%20.&amp;text=Five%20elements%20are%20using%20this,%3E%20%2C%20and%20.">According to MDN</a>, the viewBox “defines the position and dimension, in user space, of an SVG viewport.” The first two numbers are the min-x and min-y, whereas the last two numbers are the width and height of this viewport. This is in a lot of ways like a porthole window, the size of which will determine what the user can see through it. So the viewBox doesn’t set the size of the SVG, it just determines the frame or window through which we will see the SVG. For beginners, it is recommended to keep the viewBox square and somewhat larger than the SVG you are rendering. For more on the viewBox, <a href="https://webdesign.tutsplus.com/tutorials/svg-viewport-and-viewbox-for-beginners--cms-30844">check out this article by Kezz Bracey</a>.</p><h4>Conclusion</h4><p>There are benefits and drawback to using Tailwind to style the front-end of your application, but generally it can be a great framework to use quickly. SVGs are a relatively ancient technology, but are just as useful now as they were in the late 90s. I’ve covered the basics of using Tailwind to style your SVGs and get these scalable and accessible graphics into your next project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e9e3526b63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/using-svgs-with-tailwind-css-84e9e3526b63">Using SVGs with Tailwind CSS</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding useRef]]></title>
            <link>https://levelup.gitconnected.com/understanding-useref-513b1bbe00dc?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/513b1bbe00dc</guid>
            <category><![CDATA[useref]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-refs]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 22:10:01 GMT</pubDate>
            <atom:updated>2020-07-24T16:50:10.985Z</atom:updated>
            <content:encoded><![CDATA[<h4>An intro to refs and React Hooks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xFw_LxaLYxy4PuvY" /><figcaption>Photo by <a href="https://unsplash.com/@shivelycreative?utm_source=medium&amp;utm_medium=referral">Nathan Shively</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The useRef is an out-of-the-box hook in React 16.8. It is the functional component alternative to createRef() that is used in React’s class (stateful) components. Whether or not you are familiar with refs, createRef, or useRef, this article will guide you through the basics of getting started with this quite useful hook.</p><p>First off, there are two main uses for the useRef hook in a React functional component: accessing a DOM element and storing mutable information in the state without triggering a re-render of that component. We will take a look at an example of both of these and discuss some things to keep in mind along the way.</p><h4>A note of caution</h4><p>Generally, we should avoid using the useRef in React for anything that can be done <em>declaratively — </em>that is, we should let React handle the state of the app and the “how” of each component as much as possible. However, there are some situations where you need to <em>imperatively</em> alter or interact with a DOM element, telling it “how” to treat (or not treat) something, and therefore bypassing the state. Some common DOM element examples of this include managing focus on a particular element, selecting text, or media playback. We’ll also explore a few other reasons we may need to get imperative with React.</p><h4>What is a ref?</h4><p>In React, a ref is an attribute that can be used in either element tags or component tags themselves. A ref provides “a way to access DOM nodes or React elements created in the render method,” (<a href="https://reactjs.org/docs/refs-and-the-dom.html">Refs and the DOM</a>). In vanilla JavaScript, we work with DOM elements by calling document.getElementById(), passing in the id of a given element. With refs in React, we no longer need to do this. The ref attribute will literally reference that element and give us access to it’s methods.</p><p>Here is an example of putting a ref in an input tag:</p><pre>&lt;input type=&quot;text&quot; ref={textInput} /&gt;</pre><p>We can also use a ref inside of a component (but only within the render method of a parent component):</p><pre>&lt;FormComponent ref={formRef} /&gt;</pre><p>The ref attribute is the inspiration for the useRef but it is not the only reason to use this hook. Let’s get into the useRef a little more.</p><h4>What is useRef?</h4><blockquote>useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. <em>(</em><a href="https://reactjs.org/docs/hooks-reference.html#useref"><em>Hooks API Reference — React</em></a><em>)</em></blockquote><p>This is a heady definition — the basics of the useRef is that it is an object in which mutable information can be stored without triggering a re-render. The .current property is what will be initialized and where the most recent information is stored. As I’ve mentioned, this can be particularly useful for working with DOM elements but this hook is useful for a lot more than that because it can change at any time during a component’s lifecycle without triggering a re-render.</p><h4>Getting Started</h4><p>Import the useRef hook into your React component at the top:</p><pre>import React, { useRef } from &#39;react&#39;;</pre><p>Once you have the hook imported, you can begin using it. The useRef hook is initialized in the same way as the useState hook:</p><pre>const textInput = useRef(&#39;&#39;);</pre><p>The value passed into useRef will be the initial value, which is stored on .current property. In this example: textInput.current = &#39;&#39;;</p><h4>Using useRef to access elements</h4><p>Running with our example of the text input, let’s look at how we could use the useRef hook to interact with a DOM element by switching the focus to the input box:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c834a80923f6e29a8173fd61122eec78/href">https://medium.com/media/c834a80923f6e29a8173fd61122eec78/href</a></iframe><p>Here we give the button an onClick function that calls the focus() method on our useRef hook, textInput. When the button clicks, the user’s focus on the page switches to the that text box. Since we are putting the ref in the input element, we then have access to any methods for that particular HTML element, like the focus() method.</p><h4>Using useRef to store information in State</h4><p>As I’ve said a few times now, the useRef hook can store information that can be changed throughout the lifecycle of the component without triggering a re-render.</p><p>This has many use cases, but by way of example, let’s imagine we wanted to keep track of the number of times a component re-rendered. We might try to do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e8f94ae45b922b5d1301079a984dffb/href">https://medium.com/media/3e8f94ae45b922b5d1301079a984dffb/href</a></iframe><p>However, since anything stored in the state is going to trigger a re-render when it changes, every time we increment count our component will render again and thus create an infinite loop. So this is an example of something not to do! But we do need to store this number <em>somewhere</em> in the state, so the component can keep track of it over the course of its entire lifecycle.</p><p>Enter the useRef again. By simply changing count to be a useRef hook rather than a useState hook, we can safely store this mutated data without re-rendering:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3922a6eaa0d9d6f0dc3fae85b6534f9f/href">https://medium.com/media/3922a6eaa0d9d6f0dc3fae85b6534f9f/href</a></iframe><p>Note that useRef doesn’t come with it’s own setter like useState hooks do. To alter a ref we simply reassign any value stored on the .current property of the useRef.</p><p>Another note of caution: it is recommended to run any side effects, like altering a ref, inside a useEffect or a useLayoutEffect to avoid bugs.</p><h4>Conclusion</h4><p>The useRef hook is a very handy option for both interacting with DOM elements and storing mutating information in your app without triggering a re-render. However, it is suggested to only use the useRef when necessary and within a useEffect to avoid bugs.</p><p>This article is a quick introduction to the useRef hook. There is a lot going on in the world of useRef and refs in React. Here are some articles to get you started:</p><ul><li><a href="https://medium.com/@rossbulat/react-using-refs-with-the-useref-hook-884ed25b5c29">React: Using Refs with the useRef Hook</a> by Ross Bulat</li><li><a href="https://linguinecode.com/post/when-to-use-useref-and-uselayouteffect">React useRef and useLayoutEffect vs useEffect</a> by Ruben Leija</li><li><a href="https://medium.com/better-programming/how-to-properly-use-the-react-useref-hook-in-concurrent-mode-38c54543857b">How To Properly Use the React useRef Hook in Concurrent Mode</a> by Daishi Kato</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=513b1bbe00dc" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-useref-513b1bbe00dc">Understanding useRef</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deploy your Node.js app with Google]]></title>
            <link>https://levelup.gitconnected.com/how-to-deploy-your-node-js-app-with-google-2cd3771d5b21?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd3771d5b21</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[app-engine]]></category>
            <category><![CDATA[yaml]]></category>
            <category><![CDATA[cloud-shell]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 21:03:35 GMT</pubDate>
            <atom:updated>2020-07-24T16:49:53.219Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with Google Cloud Platform &amp; App Engine</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uq8Am-We32dgc1P7xhDZBA.png" /></figure><p>Google Cloud is increasingly in demand as deployment platform for developers, however, the obscurity of their documentation and sheer abundance of options can make the process quite challenging. In this post, I will walk you through the steps of setting up a project on Google Cloud and deploying a Node.js app via App Engine. These instructions are tailored for full stack apps that use React or Vue on the front-end and any Node.js server framework, but many of the principles will apply across languages and frameworks.</p><p>If you’re totally new to Google Cloud Platform (GCP), you can get started for free and, as of July 2020, take advantage of $300 in free credits for 12 months. Sign up with your Gmail account. You will need to use a credit or debit card to sign up, but Google won’t automatically charge it after 12 months.</p><h4>Create a Project</h4><p>Once you are logged in to Google Cloud, head over to the “Console.” Here is the main dashboard for all the services offered by GCP. Toward the left side of the nav bar, there will be an option to start a new project (or select a project, if you already have any existing projects with GCP). You may already have GCP projects without realizing it if you’ve used any Google APIs, like the YouTube API. In the “Select a project” view, click “NEW PROJECT” on the top right. From here, you can name your project and click “CREATE.” When you return to the GCP dashboard, make sure your new project is selected from that drop-down in the nav bar before proceeding.</p><h4>Create Application in App Engine</h4><p>Next, navigate to App Engine via the left sidebar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-ccM2B53-X4ZHwR7xlmjw.png" /></figure><p>From here, click on “App Engine” — go to the main page for this section. Here, you will be prompted to create an application. Click this button, choose a region nearest to you or your users and select “Create App.” Here you can select your language and type of environment. For this example, I will be deploying an app in Node.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*38ciEkskMjjGWfdbofPgdQ.png" /></figure><p>Whether or not you choose a standard or flexible environment will depend on your app’s needs. Generally, if you are just deploying via App Engine and not using the Compute Engine (virtual machines) or a Docker container, you will be fine with the standard environment. The good news is that you can change this later if you run into issues or your app changes. <a href="https://cloud.google.com/appengine/docs/the-appengine-environments">Read more about App Engine’s environments</a>. Click “Next” to create your App Engine app.</p><h4>Using the Cloud Shell or the Cloud SDK</h4><p>After you create your app, you will be given instructions to download the Cloud SDK. This will set you up to access your GCP project and app via your terminal on your computer. Alternatively, you can use the Cloud Shell provided in the browser. Both use the same commands to deploy your app. I won’t go into the instructions for installing Cloud SDK, but <a href="https://cloud.google.com/sdk/docs/quickstarts">you can find the quick start documentation for it here</a>.</p><p>Open up Cloud Shell by clicking the terminal icon &gt;_ on the right side of the nav bar. This is your terminal access to your GCP account. Make sure your current project is set to the project you want to deploy in — there should be bold, yellow text with your project name after your GCP name userxyz@cloudshell in the terminal. If this is not the correct project or you don’t see a project name here, use the following command to change it (replacing example-medium with your project’s name):</p><p>gcloud config set project example-medium</p><p>In addition to some GCP specific commands, you can use common bash commands in the Cloud Shell. Your home directory here is exactly like your home directory in Ubuntu or any other machine you access through the terminal.</p><h4>Deploying your app</h4><p>Now that you have successfully set up your GCP account and created your App Engine application, you can start the deployment process. For these instructions, you will need an app that has a repository stored on GitHub.</p><ol><li>Clone your repository into your home directory: <br>git clone <a href="https://github.com/HearTogether/upclose.git">https://github.com/username/reponame.git</a></li><li>Change into your repo directory: cd reponame</li><li>Install the dependencies: npm install</li><li>Set environmental variables with an app.yaml file: touch app.yaml</li><li>Run build (if needed): npm run &lt;build script name&gt;</li><li>Make sure your package.json has a working start script</li><li>Preview your app</li><li>Deploy: gcloud app deploy</li></ol><h4>Set Environmental Variables</h4><p>When you deploy on Google, the App Engine will look to set your environmental variables through an app.yaml file rather than the standard .env file. This file will also tell App Engine other information about your app’s environment. The syntax for this file is a little different than a .env:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5b016175697396e43a49d8df5797dfd/href">https://medium.com/media/d5b016175697396e43a49d8df5797dfd/href</a></iframe><p>The bare minimum that you will need in your app.yaml to deploy on App Engine is to set your runtime to whatever version of your environment’s language. Here, I have it set to Node.js version 10. If you don’t have any other environmental variables in your app, you will be good to go.</p><p>If you are following along in Cloud Shell, you can actually open up the cloud editor to edit this file. Click “Open Editor” in the top right area of the shell window. Make sure you are in the correct directory. You can either create the app.yaml in your terminal using the touch command or create it through this GUI.</p><p><a href="https://cloud.google.com/appengine/docs/standard/nodejs/config/appref">Learn more about the app.yaml and GCP here.</a></p><h4>Run the Build</h4><p>For apps built in React, Vue, TypeScript, and others that require parts or all of the code to be compiled and minified, you will need to manually run the build in the shell before you can deploy. Oftentimes this will be a script like npm run build:client. Check your package.json if you are unsure.</p><p>Note: some builds may fail if your environmental variables are undefined. This can happen because App Engine won’t start looking for your app.yaml until you deploy. If your build fails and any of your environmental variables are implicated, you may need to copy over your .env file from your development environment and then re-run the build.</p><h4>Set Start Script</h4><p>While you’re in your package.json, make sure you have a working start script to start the server. App Engine will by default use npm run start to start your app’s server when it deploys, so if you have customized your environment in another way, you will just need to make sure this script will start your server.</p><h4>Preview Your App</h4><p>You can manually run your start script in the shell and preview your app through the “Web Preview” icon on the top right of the shell window. Note that if your app uses Google’s Cloud SQL for a remote database, it may not work in preview unless you connect to the database through a proxy. I have found it easier to just deploy the app to see if it is successfully connecting to a Cloud SQL instance through the logs or as a result of my app working how I intend.</p><h4>Deploy Your App</h4><p>Once you have installed dependencies, set up your app.yaml and start script, and run your build, you can deploy! gcloud app deploy in the shell and select y to proceed. The deployment can take up to a few minutes.</p><h4>Check the Logs</h4><p>If you need to debug or see what’s going on in your deployed server’s console, you can check the logs. After deploying, you will see a command to check the logs in the shell: gcloud app logs tail. You can also find them through the App Engine &gt; Versions section in GCP’s Console.</p><h4>Conclusion</h4><p>There is a bit of a learning curve and documentation overload using Google Cloud Platform. In this article I hope to demystify the processes of deploying a Node.js application via App Engine. Once you are set up, it is as easy as pulling from your app’s origin master, checking for any new dependencies, re-running your build, and then you can easily re-deploy over and over as needed throughout development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd3771d5b21" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-deploy-your-node-js-app-with-google-2cd3771d5b21">How to deploy your Node.js app with Google</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Table Relationships in Sequelize]]></title>
            <link>https://levelup.gitconnected.com/table-relationships-in-sequelize-2e2533580c2a?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e2533580c2a</guid>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 03:59:28 GMT</pubDate>
            <atom:updated>2020-07-24T16:48:25.297Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setting foreign keys and making ORM join tables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Mt6Y5eR-2i7eZgh" /><figcaption>Photo by <a href="https://unsplash.com/@abelycosta?utm_source=medium&amp;utm_medium=referral">Abel Y Costa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Getting started with Sequelize can be a little daunting at first. But for those who are more comfortable with JavaScript and object-oriented programming, it can also make working with a database much easier. In this post, I will focus on the relational mapping aspect of this API: setting foreign keys and creating join tables.</p><h4>Introduction</h4><p>Sequelize is a Node package that carries out Object Relational Mapping (ORM) between your server or your back-end code and a SQL database (MySQL, SQLite, PostgreSQL, or MSSQL). What is ORM? It basically converts data between incompatible datatype systems (i.e. SQL and JavaScript) using object-oriented code. With Sequelize, we can use JavaScript to create the database and the tables, as well as the queries to the database.</p><h4>Models</h4><p>Rather than creating tables, Sequelize uses models to create the tables. A model will be used in your JavaScript to both store the properties (i.e. the fields or columns in a table) as well as its associations with other models/tables and it’s methods for querying the database. Similar to creating tables in SQL, when you define a model, you will also define the datatype of each key/column.</p><p>For this post, let’s imagine a database with users, projects, and a join table to track all the users by project. Before we can assign the relationships between them, we need to make the models:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb0571096e2b79ec9d5a5443e5a3e0c/href">https://medium.com/media/3bb0571096e2b79ec9d5a5443e5a3e0c/href</a></iframe><h4>Associations</h4><p>In SQL, we set foreign keys to make join tables and generally establish the relationships between tables — the database does not know what <em>type</em> of relationship your tables and their keys have. Whereas in Sequelize, we can actually declare the type of association between two tables.</p><p>There are two types of relationships in the example database:</p><ul><li>Each project has a project manager (user): one-to-one relationship</li><li>Each project can have many members (users) and each user can have many projects: many-to-many relationship</li></ul><p>After the models are established in the database, the associations can be declared. There are three Sequelize association types here: belongsTo, hasMany, and belongsToMany. Here is how these are used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdc54f8e6b46bcf142790d6988dd2cf2/href">https://medium.com/media/fdc54f8e6b46bcf142790d6988dd2cf2/href</a></iframe><p>The belongsTo &amp; hasMany associations set a many-to-one relationship. Where every project has one project manager, that project <em>belongs to</em> that user, whereas that user can <em>have many</em> projects. Sequelize will know that the foreign key for the user will be set on the project table.</p><p>Note that the column title for the foreign key can be set as the second argument in these methods. This step is not necessary — Sequelize will automatically name the foreign key user_id or userId, depending on if you have camelCase or snake_case enabled (see <a href="https://sequelize.org/master/manual/naming-strategies.html">Naming Strategies</a> in the docs). In our case, we wanted to have the id first and note that this user is the project manager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baf01bbcee9544ebe10ce01b1de07b91/href">https://medium.com/media/baf01bbcee9544ebe10ce01b1de07b91/href</a></iframe><p>For setting many-to-many associations and creating join tables, belongsToMany needs to be used on both models. Every user can <em>belong to many</em> projects, and every project can <em>belong to many </em>users. Each of these method invocations will set the foreign key in the resulting join table. Note that the through keyword sets the join table name here. You can create a many-to-many join table without creating a model, however the model can be useful if you’d like to store data in more than the default id columns (see previous example in the model section).</p><p>There are other associations that can be made in Sequelize, like one-to-one, that I haven’t covered here. Read more in the docs on all the <a href="https://sequelize.org/master/manual/assocs.html">Associations</a> that can be set in Sequelize.</p><h4>Methods</h4><p>The power of Sequelize’s models and associations are the methods they make available for querying the database. Below I have two examples, one for adding a project and another for linking the project and users in the join table.</p><p>(Note that here I used async/await — Sequelize methods are asynchronous and return promises, and you can either use ES6 promises or async/await to handle them.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e865530ee430c5c875487475420e5199/href">https://medium.com/media/e865530ee430c5c875487475420e5199/href</a></iframe><p>In the first example, addProject, we use some basic model methods to find and create records in our tables. Once we have found the user and created the new project, we need to actually <em>set</em> the foreign key. The associations established previously generate <em>getters</em> and <em>setters</em> for our model. Here, we use the custom setter, setUser, to assign the user’s id as the foreign key for the new project. Note that the entire record returned from the database needs to be passed into this method to assign the foreign key.</p><p>In the second example, joinUserProject, we are creating the join table. We need to retrieve both records, and the use another custom generated method, addUser, to join them.</p><p>Custom methods are generated for all of these associations. I have shown just two, set and add. For example, the hasMany association between projects and users generates the following special methods:</p><ul><li>project.getUsers()</li><li>project.countUsers()</li><li>project.hasUser()</li><li>project.hasUsers()</li><li>project.setUsers()</li><li>project.addUser()</li><li>project.addUsers()</li><li>project.removeUser()</li><li>project.removeUsers()</li><li>project.createUser()</li></ul><p>Read more about <a href="https://sequelize.org/master/manual/assocs.html#special-methods-mixins-added-to-instances">Sequelize Special Methods</a> in the docs.</p><h4>Which association to use</h4><p>It can be tricky to figure out which association to make, but there are a few strategies you can use to determine this. The first is to think in terms of target and source model. The source is where the foreign key comes from, and the target is the model or table where the foreign key will live:</p><pre>sourceModel.hasOne(targetModel)<br>sourceModel.hasMany(targetModel)<br>targetModel.belongsTo(sourceTable)</pre><p>This helpful code snippet above comes from <a href="https://lorenstewart.me/2016/09/12/sequelize-table-associations-joins/">Loren Stewart’s blog on the same topic</a>, and is definitely worth checking out.</p><p>The other strategy is to just try both ways, and then check the result in your database. If you don’t see the foreign key in the right place, you probably have it backwards! Here is more on why associations are defined in pairs and how to determine which to use: <a href="https://sequelize.org/master/manual/assocs.html#why-associations-are-defined-in-pairs-">Why associations are defined in pairs?</a></p><h4>Conclusion</h4><p>There is a lot more to explore in setting and working with Sequelize associations. In this post, I covered the basics of Object-Relational Mapping with Sequelize — using this ORM to set foreign keys, create join tables in your SQL database, and use some of the special methods created by these associations. Sequelize offers an approach to relational database queries that can make setting up and working with data a lot easier and faster for those familiar with object-oriented programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e2533580c2a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/table-relationships-in-sequelize-2e2533580c2a">Table Relationships in Sequelize</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say Goodbye to the Right Click]]></title>
            <link>https://medium.com/@masonk000/say-goodbye-to-the-right-click-34905ce38481?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/34905ce38481</guid>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[code-newbie]]></category>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Sun, 31 May 2020 15:36:20 GMT</pubDate>
            <atom:updated>2020-05-31T15:47:25.220Z</atom:updated>
            <content:encoded><![CDATA[<h4>Five Extremely Handy VSCode Keyboard Shortcuts</h4><p>Okay, so maybe we aren’t going to say goodbye forever to the right click, but there are some major advantages to less clicking around the screen. Using keyboard shortcuts not only saves on time, especially with repetitive tasks, but can also help you to debug faster, and come across as a more professional developer.</p><p>There are some basic keyboard shortcuts most of us use all the time, like ctrl-c or ctrl-s; and then there the some basic code editing tricks you might be using, like moving lines of code around by holding down alt and the up/down key. These are great, but there are many, many more keyboard shortcuts offered by VSCode. In this post I am going to highlight five awesome shortcuts you can start using today and give some ideas on how they can help you work faster and better.</p><h4>1. Multi-Cursor Editing</h4><p>alt-click / ctrl-alt-up/down arrow (Windows) <br>alt-click / ctrl-option-up/down arrow (macOS)</p><p>If you need to do the same thing in your code in multiple spots, you can do it all at once by adding more cursors. If the change needs to happen at the same place in the lines directly above and/or below that spot, you can use the second set of keystrokes above and not even touch your mouse! If the changes are sprinkled throughout, use your mouse to click immediately before or after each instance — and then make your changes all at once.</p><h4><strong>2. Add Cursors by Occurrence</strong></h4><p>Document: ctrl-shift-l/ Next find match: ctrl-d (Windows) <br>Document:shift-cmnd-l/ Next find match: cmnd-d (macOS)</p><p>If you’re already familiar with the alt-click trick above but want to up your multi-cursor editing game, you can actually add cursors by occurrence. Say you need to alter a variable name in your document. Rather than spending the time clicking through and manually editing each once, you can use the first keystroke set to add a cursor to every occurrence of that variable in the document, and make all those changes at once.</p><p>If you only want to edit a few of those occurrences, you can use the second keystroke to add a cursor to the next find match, and then keep pressing it to add as many cursors to as many of those successive occurrences as you want. Note that this only moves <em>down </em>the lines of your code, so you’ll want to start your cursor at the first occurrence and move down.</p><h4>3. Expand or Shrink Selection</h4><p>shift-alt-right/left arrow (Windows) <br>ctrl-shift-cmnd-right/left arrow (macOS)</p><p>You can easily select entire code blocks (from the opening curly brace to the closing curly brace). Arrow to the right more, and you will expand selection to the next outer code block. Arrow to the left, and you will shrink selection down. This is not only helpful for selecting and moving parts of your code around, but also for locating stray curly braces or identifying the full scope of a complex code block (such as any callback hell you might find yourself in).</p><h4>4. Open and Close Various Tools</h4><p>This isn’t for quick <em>editing</em> <em>per se</em>, but I wanted to highlight a few shortcuts for opening or toggling tools and views in VSCode you might frequently use. It can be helpful to close these views when you don’t need them, to keep the visual clutter down and be able to see more of your code while editing — and with a quick keystroke, you can open them back up only when you need them!</p><p>Windows keystrokes are listed first, followed by macOS:</p><ul><li>Terminal: ctrl-backtick or ctrl-j / cmnd-backtick or cmnd-j</li><li>Sidebar: ctrl-b / cmnd-b</li><li>Debugger: ctrl-shift-d / shift-cmnd-d</li></ul><h4><strong>5. Format Document/Selection</strong></h4><p>Document: shift-alt-f / Selection: ctrl-f-k (Windows) <br>Document: shift-option-f / Selection: cmnd-f-k (macOS)</p><p>If you’re using a linter to correct your syntax, these two format shortcuts are great. A couple keystrokes and all of your errors are fixed. If you are hesitant to format your whole document, you can select a portion of your code and use this selection shortcut. I will admit, the f and the k are a little far apart on a QWERTY keyboard. If you are a selection-leaning formatter, then you could consider changing the key bindings for this shortcut.</p><h4>View &amp; Change the Shortcut Keybindings</h4><p>ctrl-k-s (Windows) <br>cmnd-k-s (macOS)</p><p>Open the Keyboard Shortcuts to change the keybindings for any of them, or just peruse all the options VSCode offers. Hover over any of these shortcuts, and you can click the pencil icon on the left to edit — when the dialog box pops up, just press your preferred keystrokes for that shortcut to change it. That’s it!</p><h4>Conclusion</h4><p>Getting more comfortable with keyboard shortcuts has several advantages. The first cool thing about some of these shortcuts is that, in addition to cutting back on some of the tedium of repetitive code tasks, they can also seriously help you find or clear up issues in your code. It also looks good — being able to move around your files and in VSCode smoothly and quickly is a huge asset to any team.</p><p>This is just a small taste of the things you can accomplish faster with shortcuts. The full lists of keyboard shortcuts for macOS, Windows, and Linux are below. Enjoy!</p><p><a href="https://code.visualstudio.com/docs/getstarted/tips-and-tricks">VSCode’s Tips &amp; Tricks</a></p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/89dc30305927bbddf461b4e68dd0dfca/href">https://medium.com/media/89dc30305927bbddf461b4e68dd0dfca/href</a></iframe><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/a729ee9acfe5000b46fac9967419297d/href">https://medium.com/media/a729ee9acfe5000b46fac9967419297d/href</a></iframe><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/c11fbddc48b83320c0b8468632c44fc1/href">https://medium.com/media/c11fbddc48b83320c0b8468632c44fc1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34905ce38481" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combining Data in SQL]]></title>
            <link>https://medium.com/swlh/combining-data-in-sql-51871b5f7e60?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/51871b5f7e60</guid>
            <category><![CDATA[database-management-sys]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Sun, 24 May 2020 23:11:40 GMT</pubDate>
            <atom:updated>2020-05-24T23:11:40.647Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting a grip on inner, right, left, &amp; full joins</h4><p>Before we get started, let’s make sure we are all on the same page. In this article, I am going to breakdown the different ways we can join data in SQL. What is SQL, you ask? SQL, pronounced either as “es-que-el” or “sequel,” depending on who you ask, stands for Structured Query Language — it is the language used to interact with a SQL relational database. This includes MySQL, as well as a whole host of other database management systems, including Oracle and Microsoft Access.</p><p>This query language is different from imperative programming languages, like JavaScript, that use complex syntax to state how to do something. SQL looks more like English sentences, using declarative statements to say what needs to happen. There are a few very common and straightforward SQL commands, like select, insert, and delete that are used to view or modify tables — which is where data is stored in relational databases. In this post, we are going to take a closer look at a tricky SQL command used to combine data from two or more tables: join.</p><h4>Why join tables?</h4><p>There are often instances where not all of the information needed can be easily or usefully stored in one table. For example, if you run a business, you may keep track of your customers in one table and their orders in another table. Because any one customer can have any numbers of orders, we would understand the <em>relationship</em> between these two tables to be a <em>one-to-many</em> relationship. However, we may need to lookup all the orders from a particular customer. This is where the join comes in.</p><h4>Primary &amp; Foreign Keys</h4><p>Before we can begin a join, we need to make sure the two tables are connected. In SQL, this is done by declaring a <em>primary key</em> in one table, and linking it to the other table as a <em>foreign key</em>. In a many-to-one relationship, the many table will have a foreign key for the one it is linked to. In our example, the orders table would have a field to track the customer for each order. We would use the customer id as a foreign key in each order record in the orders table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccMcue1OVEfEZVNC2qZTiw.png" /><figcaption>Diagram of our example database with two tables: customers and orders.</figcaption></figure><p>In our customers and orders table, there are some customers who are registered but don’t have orders, and there are some orders that are not linked with a customer in the database. This will come into play in thinking about the different kinds of joins we can do with this example database.</p><h4>Inner Join</h4><p>The most common join is the inner join, which will return rows where there is a match in both tables. In our example, we may want to see all customers that placed orders and any details about those orders. For that, we would use the following commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ad19c6d9d59ea1596ddbe3532eddc26/href">https://medium.com/media/8ad19c6d9d59ea1596ddbe3532eddc26/href</a></iframe><p>The inner join is like the inner overlap in a Venn diagram — some of one table and some of another, but most likely not all of any one table. In our example, the orders without customers and the customers without orders would be excluded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/0*Q2AczKFMhA8pdE0M.png" /><figcaption>image from <a href="https://www.dofactory.com/sql/join">https://www.dofactory.com/sql/join</a></figcaption></figure><h4>Left (Outer) Join</h4><p>If we wanted to see all of the customers with their order details added, we could use a left join. This would give us <em>all </em>of the records <em>from </em>the customers table, with all their order details. This would also give us some customers who don’t have any orders at all. It would not, however, show us any orders that were not linked to a customer in the database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04a9ff12267ed441a5678adb53023337/href">https://medium.com/media/04a9ff12267ed441a5678adb53023337/href</a></iframe><p>Note that we declare the left table on line 2 after the from operator. This sets the relationship between the two tables, pulling all the data from the table on line 2, and anything linked to it from the table on line 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*q40gjcn_oDYF-hEjFi2bkw.png" /><figcaption>image from <a href="https://www.dofactory.com/sql/join">https://www.dofactory.com/sql/join</a></figcaption></figure><h4>Right (Outer) Join</h4><p>The right join is the opposite of the left join. In our example, we could use the exact same syntax as our left join, replacing only the word <em>right </em>with <em>left</em>, to see all the orders and any customer details linked to them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b1d2ccc42657a06329a6f3d6bf1f98b/href">https://medium.com/media/4b1d2ccc42657a06329a6f3d6bf1f98b/href</a></iframe><p>Again, note that we declare the customers table on line 2, but in this instance, since we making a right join, we will be pulling all of the records from the right table, orders. In this join table, there will be some orders with no customer information to show.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Oow2yIo5PYYZA8GB9f4GUg.png" /><figcaption>image from <a href="https://www.dofactory.com/sql/join">https://www.dofactory.com/sql/join</a></figcaption></figure><h4>Full (Outer) Join</h4><p>Lastly, if we wanted to see all of the records combined, we could execute a full join. This would pull in all the orders, even those without a linked customer, as well as all the customers, even those that had not placed an order yet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9ea56d5955b71c7176b3a2e9530a9b4/href">https://medium.com/media/e9ea56d5955b71c7176b3a2e9530a9b4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*pf0W7PGXT8De7iFd_alOMw.png" /><figcaption>image from <a href="https://www.dofactory.com/sql/join">https://www.dofactory.com/sql/join</a></figcaption></figure><h4>Conclusion</h4><p>Your first forays into making join tables in SQL may be confusing. Before starting a join, make sure you know if you need all the records from a table, or just some of them. If you need all the records from any table, you will probably need to do a right or left join. To keep it simple, you could always do a left join, and declare the table after from as the table you want all the records from, followed by the table you only want some of them from.</p><p>If you only need some records from both tables, that is an inner join. If you need every single record in the database in one join table, that’s going to be a full join.</p><h4>References</h4><ul><li><a href="https://www.w3schools.com/sql/sql_join.asp">W3Schools.com</a></li><li><a href="https://www.tutorialspoint.com/sql/sql-primary-key.htm">SQL - Primary Key</a></li><li><a href="https://www.dofactory.com/sql/join">SQL JOIN</a></li><li><a href="https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/">SQL Joins (Inner, Left, Right and Full Join) - GeeksforGeeks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51871b5f7e60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/combining-data-in-sql-51871b5f7e60">Combining Data in SQL</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 Deep Dive: Iterables & Iterators]]></title>
            <link>https://levelup.gitconnected.com/es6-deep-dive-iterables-iterators-fee729db692f?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fee729db692f</guid>
            <category><![CDATA[iterables]]></category>
            <category><![CDATA[for-of-loop]]></category>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Sun, 17 May 2020 02:29:36 GMT</pubDate>
            <atom:updated>2020-07-24T16:49:31.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CgdwZ_Cceags89Mt" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybishop?utm_source=medium&amp;utm_medium=referral">Jeremy Bishop</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Looping over data structures in JavaScript ES6</h3><p>Today I am going to take a closer look at the new ways we can navigate data structures in the 6th edition of the ECMAScript standard — commonly referred to as ES6. Among all the upgrades and syntactical sugar added to JavaScript in 2015, there is also now support for iterators and iterable objects. These not only allow for less code when iterating over arrays and strings, but support new collections, like maps and sets, and the creation of custom objects and iterators for them. You could think of these as similar to (but not the same as) the looping that happens in a for-in loop on steroids.</p><p>Okay, you might be wondering, what even are iterators and iterable objects? An <strong>iterable</strong> is a sequential data structure that can be iterated over. Iterables can also have their own access method, which defines its <strong>iterator</strong>. This allows iterables to be publicly accessible. An iterator<strong> </strong>is like a pointer that traverses the collection in a particular way. As we will get into in a bit, these new custom iterators in ES6 can loop through more than just a simple array.</p><p>This is a lot of jargon that I will break down in a few minutes with an example. But for starters, let’s take a look at the default use of ES6 iterators in the for-of loop.</p><h4>The for-of loop</h4><p>In ES5 and before, we’re used to seeing for and while loops to iterate over arrays or strings. Now, with ES6, we can hop around an array or a string without having to set the parameters for these loops. The for-of loop by default knows how to iterate over these data types sequentially:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2901fc736e514be6873f24593d248c4/href">https://medium.com/media/a2901fc736e514be6873f24593d248c4/href</a></iframe><p>In these examples, the array and the string are now both <em>iterable</em> data structures, and when we use the for-of loop to iterate over the collection, we declare a variable name for the <em>iterator </em>to use<em>— </em>such as x or char.</p><h4>Adding Map &amp; Set</h4><p>In addition to quickly navigating arrays and strings, the for-of loop can also be used on maps and sets — both of which are also now readily available in ES6. Both data structures can be initialized using the new keyword (following the pseudoclassical instantiation pattern).</p><p>Maps are not too different from standard objects, except that their key-value pairs are ordered. Sets are more like arrays — a collection of ordered values — however, each value can only exist once in a set. I won’t get too much into maps and sets in this post, but will show a quick example of using the for-of loop on a map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5a7b6a574f6ba614c8cb5df85b3c005/href">https://medium.com/media/f5a7b6a574f6ba614c8cb5df85b3c005/href</a></iframe><h4>Iterate or …enumerate?</h4><p>You may have noticed that objects aren’t showing up here, even though I mentioned iterable objects at the beginning. The reason is that out-of-the-box <strong><em>JavaScript objects are not iterable data structures, but rather are enumerable </em></strong>— they don’t have an internal order in the way that arrays, strings, and now maps and sets do. Objects contain an unordered collection of key-value pairs. We can still, however, use the for-in loop to enumerate over an object’s keys and/or it’s values. But, as we will see, we can also create custom iterable objects and iterators in ES6.</p><h4>Symbol.iterator</h4><p>While for-of loops are by default accessible to arrays, strings, sets, and maps — ES6 also allows for custom iterables and iterators using the Symbol.iterator. The symbol is a new primitive data type in ES6. This one defines iterators and iteration processes for any collection of any size and complexity. It works like a method on an object, and as such, the Symbol.iterator is stored as a key on a custom iterable object. It can also be used to define an iteration pattern to be used on provided JavaScript data structures. The Symbol.iterator is also the code that is happening behind the scenes to make the for-of loop work by default for the aforementioned data structures.</p><p>To keep things simple and get a feel for how this symbol works, let’s build an iterator that will loop through arrays in reverse. In this example we won’t be adding the symbol as a key on a custom object because it will be used on arrays — so this one is a standalone iterator. But the structure of the Symbol.iterator would be similar if it were a key in a custom iterable object. First, we will create the reverse iterator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/916c66d53d2401235eaef4c9ef8422fa/href">https://medium.com/media/916c66d53d2401235eaef4c9ef8422fa/href</a></iframe><p>Similar to a for loop, we are going to track the index and start at the end of the collection (line 3). The Symbol.iterator uses the next key to define when and how to iterate (line 5). All iterators look to this next method to define its iteration pattern. In our reverse iterator, every time next() is called, it will traverse backwards through the structure (line 6), stopping when i is less than zero (line 7).</p><p>Now, we can call reverse in a for-of loop, and <em>voilà</em>! Iterate in reverse over an array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8259ac6c383d50390fcd8a57ee7afc8/href">https://medium.com/media/a8259ac6c383d50390fcd8a57ee7afc8/href</a></iframe><p>Note in the example above that iterators aren’t limited to for-of loops: they can also be used with spread operators in ES6. On line 8, the spread operator applies the reverse iterator to our array, spreading out the result.</p><p>In conclusion, we took a look at some of the quick ways ES6 lets us loop through a whole host of data types with the for-of loop — from arrays, to strings, and the newly available sets and maps. And we got our toes wet in an introduction to building our own iterators with Symbol.iterator. It’s plain to see that getting familiar with for-of loops, iterators, and iterables in JavaScript’s ES6 will not only shorten our code but open up a whole other dimension of custom data structures and tools we can use to navigate them and access the information they store.</p><p>References — go even deeper into ES6 iteration:</p><ul><li><a href="https://www.digitalocean.com/community/tutorials/js-iterables">Introduction to Iterables and Iterators in JavaScript</a> by Vijay Prasanna</li><li><a href="https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/">ES6 In Depth: Iterators and the for-of loop</a> by Jason Orendorff</li><li><a href="https://www.freecodecamp.org/news/demystifying-es6-iterables-iterators-4bdd0b084082/">Demystifying ES6 Iterables &amp; Iterators</a> by Tiago Lopes Ferreira</li><li><a href="https://codeburst.io/a-simple-guide-to-es6-iterators-in-javascript-with-examples-189d052c3d8e">A Simple Guide to ES6 Iterators in JavaScript with Examples</a> by Arfat Salman</li><li><a href="https://towardsdatascience.com/javascript-es6-iterables-and-iterators-de18b54f4d4">Javascript ES6 — Iterables and Iterators</a> by Deepak Gupta</li><li><a href="https://medium.com/better-programming/what-is-the-difference-between-for-in-and-for-of-in-javascript-650952654e97">What is the Difference Between ‘for…in’ and ‘for…of’ in JavaScript?</a> by Jonathan Hsu</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fee729db692f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/es6-deep-dive-iterables-iterators-fee729db692f">ES6 Deep Dive: Iterables &amp; Iterators</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Two Stack Queue]]></title>
            <link>https://medium.com/@masonk000/a-two-stack-queue-c119cec276e6?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c119cec276e6</guid>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Mon, 11 May 2020 04:01:01 GMT</pubDate>
            <atom:updated>2020-05-11T04:01:49.623Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a queue from two stacks in JavaScript</h4><p>Initially, the idea of building a queue from two stacks made no sense to me. Why would you use two collections to create one collection? But as I explored the toy problem, and considered the challenge of queues in JavaScript, it all made so much sense.</p><p>First, let’s get the basics of the stack and the queue out of the way. Both of these collections are related to each other by being either first in, first out (FIFO) or first in, last out (FILO). Stacks, like a pile of dishes, are first in, last out. You’re gonna have to wash all those other dishes first before you are going to get to that first dish. Queues, on the other hand, are FIFO — like a line, the first in is going to be the first out.</p><p>In a stack, items are stored with a key that relates to its position in the stack. Stacks have methods that are similar to an array, we can pop the top item off, and we can push a new item onto the top of the stack. We can’t pull from anywhere else in the stack.</p><p>With a queue, we can add to the end of the line, and remove from the front of the line. Native JavaScript collections, arrays and objects, don’t come out of the box with a way to navigate a queue easily — we would have to completely rearrange an array every time an item leaves the queue. But if we make it with two stacks, and build some methods to use these two stacks behind the scenes, managing a queue becomes quite simple.</p><p>Let’s get into the code:</p><p>First, we initialize the Queue class with two instances of a Stack, one for the inbox and one for the outbox:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*Wby2geV1c9EA5x7uQwi2Hg.png" /></figure><p>We will need three methods to navigate our queue: an enqueue (to add items), a dequeue (to remove items), and one to get the size of the queue.</p><p>The enqueue is the most simple — let’s use the stack’s push method to add the item to the inbox:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*moQpswwvAVl0UXMReqZVpA.png" /></figure><p>It’s in the dequeue method that things get interesting. In order to simplify the process of getting to the front of the line and pulling that item out, each call to dequeue is actually going to pull the first item from the inbox, <em>from the end</em> of the outbox. If the outbox is empty, it will move all the items from the inbox to the outbox <em>in reverse</em>, and then pop the last item from the outbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*8FBmx4eJviUNfc8_iyULOQ.png" /></figure><p>Both of these methods rely on a size method that will track the total size of the queue. It’s a simple one, just add up the sizes of both inbox and outbox at any given moment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*r4u3Fcoz57jaKRd4m3zmnw.png" /></figure><p>While this is using prototype methods for a Stack class that builds the stack inside an object, this could also be build with an array, using the array’s prototype methods: pop and push. The size method would need to return the length of the inbox and outbox, but everything else would work just the same.</p><p>This was a fun puzzle to put together, and now that I’m on the other side of it, I can’t think of an easier way to build a queue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c119cec276e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Binding in JavaScript]]></title>
            <link>https://medium.com/@masonk000/function-binding-in-javascript-c348fd97bd9a?source=rss-9e46da7111a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c348fd97bd9a</guid>
            <dc:creator><![CDATA[Kris Mason]]></dc:creator>
            <pubDate>Mon, 04 May 2020 03:40:31 GMT</pubDate>
            <atom:updated>2020-05-04T03:40:31.347Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding this &amp; how it is defined by function invocation</h4><p>In JavaScript, we often build functions and methods to re-use code blocks throughout the larger program. However, depending on how it is invoked, functions and methods will by default refer to certain objects. Whatever default object that is may not always be desirable, which is where the this keyword comes in.</p><h3>this</h3><p>The this keyword enables functions in JavaScript to be reused in different contexts — it helps make it possible to point the function to a particular object and all of its properties when it is invoked. However, simply using this in a function or method won’t bind it to the object it is <em>used</em> in. <strong>Functions are bound to a particular context at call time, not when they are declared.</strong></p><p>This is similar to how parameters are only defined at call time. Just as we need to look to the arguments passed in at call time to know the value of a function, we need to look to how the function is invoked to determine what object this will bind to. In order to suss out the context for this at call time, we will need to know the five types of function binding and how they work.</p><h3>Window Binding</h3><p>The most basic function binding is the default or window binding. When a function is freely invoked, such as myFunc(), it will always look to the global object for its context. In browsers, the global object is the window, or [object Window]. This is the fall back binding for all functions, and is most often identifiable when a function is called without using dot notation, otherwise known as free function invocation.</p><h3><strong>Implicit Binding</strong></h3><p>One of the most common ways the binding of this is defined is through implicit binding, which is another way of saying onject method binding or method invocation. This is when a function is called as a method of an object using dot notation. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*R5_q9v1PuhCR8jfzbOLF9w.png" /><figcaption>Example of explicit binding through method invocation.</figcaption></figure><p>In this example, the method would alert: ‘My name is Kris.’ We can tell that this is implicitly bound through method invocation by looking to “the left of the dot.” If the method is part of an object, and is called as such, this will be bound to that object’s context. In this example,message() looks for the name property within getName to define this.name.</p><h3>Explicit Binding</h3><p>Whereas implicit binding uses method invocation to attach this to a particular object, there is another way to attach this when functions are not stored as methods on an object — explicit binding. Explicit binding forces a function call to bind to a particular context object, by using either call, apply, or bind. These are predefined JavaScript methods — properties inherited by all function through the Function.prototype.</p><p>To give a standalone function a particular this context at call time, simply use one of these methods on the function, passing in the desired context object as the first argument. Of course, these three methods don’t do the exact same thing. Let’s look at the basic differences:</p><h4>.call()</h4><ul><li>immediately invokes the function</li><li>first parameter is the context object</li><li>all other parameters are individually listed, separated by comas</li></ul><h4>.apply()</h4><ul><li>immediately invokes the function</li><li>first parameter is the context object</li><li><strong>all other parameters can be passed in as a single array</strong></li></ul><h4>.bind()</h4><ul><li>does <em>not</em> immediately invoke the function</li><li>returns <strong>a new function that can be invoked later in the code</strong>, while maintaining the desired context binding — this is useful for passing functions into other functions, like setTimeout(), which will invoke it later and won’t necessarily bind the invoked function to the correct object without being coerced</li><li>first parameter is the context object</li><li>all other parameters are individually listed, like with call</li></ul><p>Syntax examples for call, apply, and bind:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*GzDWvirTJWkHZlsZ7Li4Gg.png" /><figcaption>Syntax examples for explicit binding with call, apply, and bind function methods.</figcaption></figure><h3>new Binding</h3><p>The new operator used before a function call will also bind a particular context object to that invocation. However, new is not used for any kind of function call, but for constructor function calls. When new is used, the function’s parameters will be used to instantiate or create a new object with its own this context. So, with the use of new we know the context of this for that new object — it’s own. Functions called with new are named with title case, as opposed to the JavaScript naming convention, camel case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*f_wR8nCA_bPoB_Z0RNK7Sg.png" /><figcaption>Example of new operator used when invoking a constructor function to create a new object.</figcaption></figure><h3>Lexical Binding</h3><p>In ES6, we can use arrow functions for syntactical simplicity. However, functions declared with the function keyword are not interchangeable with arrow functions, and the primary difference is the way they handle this. Whereas standard functions have their own this, arrow functions do not, and are always referring to the outer scope when this is referenced. As Mahendra Choudhary says, “the this value used in arrow functions is actually fetched lexically from the scope it sits inside.”</p><p>The lexical binding refers to how this can also be bound by the type of function used. This can make for less code when you want a function to inherit this from the outer scope, or can cause problems when you’d like to pass a context into a function.</p><h3>Look to the invocation <em>and the declaration</em></h3><p>The way a function is declared turns out to be just as important as the way it is invoked in determining the context for a function. At invocation, we can immediately see if it is default, implicit, explicit, or using the new keyword.</p><p>If a function is called freely, without the use of dot notation, it most likely is bound to the global window object. If a function uses dot notation, either for method invocation or using one of the Function.prototype properties, it will be bound to the object to left of the dot or as the first argument. And if a constructor function is used to create a new object, there will be a new keyword before it and that object will have it’s own content. However, if any function is declared with an arrow function, it can’t have a this property of its own, or have one passed into it — it will always look to the parent scope for a this to bind to.</p><p>Sources:</p><ul><li><a href="https://www.w3schools.com/js/js_this.asp">The JavaScript this Keyword</a>, w3schools</li><li><a href="https://medium.com/@iampika/es6-arrow-functions-syntax-and-lexical-scoping-d061732071e7">ES6 arrow functions, syntax and lexical scoping</a> by Mahendra Choudhary</li><li><a href="https://tylermcginnis.com/this-keyword-call-apply-bind-javascript/">Understanding the “this” keyword, call, apply, and bind in JavaScript</a>, by Tyler McGinnis</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c348fd97bd9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>