<?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 Anna Peterson on Medium]]></title>
        <description><![CDATA[Stories by Anna Peterson on Medium]]></description>
        <link>https://medium.com/@annapeterson89?source=rss-afe638e475e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*YNwZytNE0E0mX-87pwwK-g.jpeg</url>
            <title>Stories by Anna Peterson on Medium</title>
            <link>https://medium.com/@annapeterson89?source=rss-afe638e475e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:28:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@annapeterson89/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[The World’s Easiest “The Rock” Themed Rock Paper Scissors JavaScript Tutorial]]></title>
            <link>https://javascript.plainenglish.io/the-worlds-easiest-the-rock-themed-rock-paper-scissors-javascript-tutorial-ee99b7f83e69?source=rss-afe638e475e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee99b7f83e69</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[humor]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Anna Peterson]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 08:49:59 GMT</pubDate>
            <atom:updated>2020-06-19T08:49:59.451Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you’ve ever wanted Dwayne “The Rock” Johnson to teach you JavaScript, well, this isn’t your lucky day, but it is </em><strong><em>almost like</em></strong><em> your lucky day!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWWQmgjIoPYLgOPUfNODzw.jpeg" /></figure><p>It’s a new spin on an old game, but I found the <a href="https://annaelizabeth2019.github.io/the-rock-paper-scissors-2/">finished product</a> to be weirdly amusing! Best of all, you can throw this game together in an afternoon and send it to all your friends for a laugh.</p><p>This tutorial is written in vanilla JS, CSS, and HTML. It is written with a <strong>beginner</strong> in mind. If you aren’t an absolute beginner, have fun anyway! Please build on the tutorial here and send me what you come up with! I would love to see it. At the end we will have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*nogG1FS4Id65l7iEivaYYg.png" /></figure><p>Here’s a link to my repo on Github and my own <a href="https://annaelizabeth2019.github.io/the-rock-paper-scissors-2/">finished game</a>.</p><h3>Finally! The Rock is home</h3><h4>Game requirements:</h4><ul><li>Users have 3 choices: The Rock, paper, or scissors</li><li>Users can select a new move every round</li><li>Computer can automatically select a new move every round</li><li>The game will select a random image associated with the player’s choice of move and display it</li><li>Keeps score</li><li>Displays a winner for every round</li><li>Is funny</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0a_H4TsL38Hu0vCmI1XIcw.jpeg" /><figcaption>Japan — where the world’s most dramatic RPS tournament is held</figcaption></figure><h4>Mobile First</h4><blockquote>Excuse The Rock For One Second, His Cell Phone Is Going Off. Hello? Hey It’s Nothing. He Says He Knows You!<br>- Dwayne “The Rock” Johnson</blockquote><p>Please consider styling your game for mobile users.</p><p>You can do whatever you want with the design of this project. This tutorial will focus on the JavaScript after providing you with my basic HTML and CSS. However, I want to include a note on mobile-first design while we’re getting set up.</p><p><em>Mobile First </em>means designing for mobile before any other platform. Most users interact with the web through mobile devices so it makes sense to let that guide our choices when building this game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*910ZzADkv-iygErkaGq_Rg.png" /><figcaption><a href="https://medium.com/@BuildMySite1/how-phablets-are-changing-mobile-ux-1bf2949d14b4">illustration of The Thumb Zone via Darlene Tate</a></figcaption></figure><p>When we look at the <a href="https://medium.com/@BuildMySite1/how-phablets-are-changing-mobile-ux-1bf2949d14b4">natural movement of a user’s thumb</a>, we see that the bottom of the screen is most reachable. <a href="https://www.smashingmagazine.com/2016/09/the-thumb-zone-designing-for-mobile-users/">Smashing Magazine</a> has more on this. Even when I was still in school, friends who I sent my projects to would want to open them on their smartphones. Projects that don’t translate to mobile will be difficult to share with others, even when they’re simple.</p><p>All you need to do is use your dev tools (on Chrome, hit <em>cmd + option + i</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*BDRTzfWtikefLvzWY8HCxg.png" /></figure><p>Hit the icon above and you’re all ready to design for mobile users!</p><p>When it comes time to look at the desktop version, you can customize the CSS with a line like this:</p><pre><em>@media</em> only screen and (min-width: 600px)</pre><p>You will be able to see how I do this in the simple CSS I’ve provided below.</p><h3>Do you smell what The Rock is cooking?</h3><h4>File Set-Up</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKzmgnQRc3WxU3Ty2SYk7Q.jpeg" /><figcaption>via <a href="https://www.flickr.com/photos/ohhsnap_me/">Megan Elice Meadows</a></figcaption></figure><p>You only need <strong>index.html</strong>, <strong>main.css</strong>, <strong>main.js</strong>, and any images you want to use.</p><h4>HTML Setup</h4><p>When I set up my HTML, I like to think about the layout of the page and divide it into boxes based on the <a href="https://99designs.com/blog/tips/6-principles-of-visual-hierarchy/">hierarchy of information</a>. <em>The hierarchy of information</em> is a fancy way of saying the important stuff should be the easiest to see. For our game, I want the buttons to go near the lower portion of the screen where the user’s “thumb zone” will be, kind of like you might find on Instagram. I want pictures of each player’s choice above the action buttons and a score at the top. We will track the player’s score, the computer’s, and the ties. At the very top, I’ve got the game title. This game is so intuitive that I won’t bother with directions, but you can feel free to choose something like, <em>“SELECT YOUR WEAPON!”</em></p><p>To make this game <strong>more accessible to screen readers and more searchable</strong>, I‘ve used <a href="https://www.freecodecamp.org/news/semantic-html5-elements/">semantic HTML elements</a>, not only divs.</p><p>The layout:</p><p>body &gt; header, main, aside with RPS buttons, optional links for shameless self-promotion</p><p>main &gt; scores table, aside with images</p><p>Go ahead and try to set your HTML on your own and come back when you&#39;re done to see if it looks like mine. Feel free to modify the layout if you want.</p><p>My HTML ends up like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c98db6924e5ba29609abb33856cf483/href">https://medium.com/media/3c98db6924e5ba29609abb33856cf483/href</a></iframe><h4>CSS Setup</h4><p>I’m using <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">flexbox</a> to get everything centered and aligned. My CSS is spartan so, please, go wild and scrap or keep whatever seems right to you. All I ask is that you take a little time to see what I’ve done before moving on.</p><p>be sure to <a href="https://www.w3schools.com/css/css_howto.asp">link</a> your CSS and HTML with a line like this in the &lt;head&gt; of your HTML:</p><pre>&lt;link <em>rel</em>=”stylesheet” <em>href</em>=”css/main.css” /&gt;```</pre><p>You will have to change the href attribute to match up with the path to your CSS stylesheet.</p><blockquote>There are two things you can do about it, and that’s nothing and like it!<br>- Dwayne “The Rock” Johnson</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b0c24366b7ea9f0a5bbe54d039a1d31/href">https://medium.com/media/1b0c24366b7ea9f0a5bbe54d039a1d31/href</a></iframe><h4>JS Setup</h4><p>Next, we’ll want to get started with your JS. Just like we linked up the CSS stylesheet, we need to link up the JS script tag.</p><pre>&lt;script <em>defer</em> <em>src</em>=&quot;js/main.js&quot;&gt;&lt;/script&gt;</pre><p>Be sure to include that <a href="https://www.w3schools.com/tags/att_script_defer.asp">defer</a> tag. It will keep our JS from loading before we have a fully parsed DOM.</p><p>In your JS file, use a console log to confirm that it’s working:</p><pre>console.log(&quot;hello world!&quot;);</pre><p>Using your dev tools, you can click the console button and see the message! You always want to establish that the JS and HTML are properly linked <em>before</em> doing any significant work so you can be sure you didn’t forget your script tag or use a bad path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*mReMzwdsdmcw8UlLSFsdgg.png" /><figcaption>You can ignore any <a href="https://www.w3.org/2005/10/howto-favicon">“errors” from favicon</a> if you’ve made it this far!</figcaption></figure><h4>Image Setup</h4><p>Usually, you would have only one image for each weapon, but I couldn’t pick <em>just one</em> photo of Dwayne “The Rock” Johnson so I’m going to randomly select an image to display for each weapon every turn. It makes things a little more fun and unpredictable in this simple game of chance. Spend a few minutes (or hours — I don’t know what kind of time you’ve got on your hands) finding fun images to use for your project and save them to an images file in the root of your project or just use the URLs. Feel free to come up with your own theme or spin on the game! Most personal non-commercial usage of photos you find online is probably fine, but you can also filter searches on <a href="https://www.flickr.com/">flickr</a> and Google by copyright or try one of these royalty-free photo sites:</p><ol><li><a href="https://unsplash.com/">Unsplash</a></li><li><a href="https://gratisography.com/">Gratisography</a></li><li><a href="https://morguefile.com/">Morguefile</a></li><li><a href="https://pixabay.com/">Pixabay</a></li><li><a href="http://www.stockvault.net/">Stockvault</a></li><li><a href="https://www.pexels.com/">Pexels</a></li><li><a href="https://picjumbo.com/">Picjumbo</a></li><li><a href="https://www.pikwizard.com/">Pikwizard</a></li><li><a href="https://www.rawpixel.com/">Rawpixel</a></li><li><a href="https://www.reshot.com/">Reshot</a></li></ol><p>We have a couple of options for our image elements: create a &lt;div&gt; and change its background image with JS or create an image and change its <strong>source</strong> with JS. Background images are nice because they’re less likely to mess up the layout of your page than images of varying sizes, but I’m going to go with an &lt;img&gt; element and change the source. I consider these images to be part of the <strong>content</strong> of this game rather than a background and, unlike divs, images come with an <a href="https://www.w3schools.com/tags/att_img_alt.asp">alt attribute</a> that allows <strong>screen readers</strong> to work better so our application is more accessible and searchable. Be sure to test all your images out and make sure that the sizes all work alright and adjust your CSS if you need to. <strong>Square</strong> images of ~500+px are best.</p><h3>Make a Plan</h3><p>So, I’m going to think about my game and break it into some different pieces. Go through each question and see if your answers match up with the ones I came up with.</p><p>What will need to change on the page? (<strong>cached element references</strong>)</p><p>My answers:</p><ul><li>Images</li><li>Scores</li></ul><p>What will we keep track of in memory? (<strong>state</strong>)</p><p>My answers:</p><ul><li>Scores for computer, player, and ties</li><li>Winner, if there is one</li><li>Available images associated with each weapon</li><li>The available weapons and which opponent they can defeat</li></ul><p>What user actions will we need to know about? (<strong>event listeners</strong>)</p><p>My answers:</p><ul><li>Clicking an attack move</li></ul><p>What actions will we need to do? (<strong>functions</strong>)</p><p>My answers:</p><ul><li>Respond to a player selecting a move</li><li>Determine a winner</li><li>Display the results</li></ul><p>The plan is to break down each bullet point above into a piece of code. When that’s done, we’ll have a game!</p><h3>Cached Element References</h3><h4>Scores</h4><pre><em>// --- cached element references ---</em></pre><pre><em>// SCORES</em></pre><pre>const pScore = document.getElementById(&quot;player-score&quot;);<br>const cScore = document.getElementById(&quot;computer-score&quot;);<br>const tScore = document.getElementById(&quot;tie-score&quot;);<br>console.log(pScore, cScore, tScore);</pre><p>I’ve included a console.log so we can see what each of these variables look like in our console and be sure we’re grabbing HTML elements on our page.</p><p>In order for this part to work make sure that the element containing the scores have the correct id attribute, for example:</p><pre>&lt;tr&gt;<br>  &lt;td id=&quot;player-score&quot;&gt;0&lt;/td&gt;<br>  &lt;td id=&quot;tie-score&quot;&gt;0&lt;/td&gt;<br>  &lt;td id=&quot;computer-score&quot;&gt;0&lt;/td&gt;<br>&lt;/tr&gt;</pre><p>Now, if I do this:</p><pre>const pScore = document.getElementById(&quot;player-score&quot;);<br>const cScore = document.getElementById(&quot;computer-score&quot;);<br>const tScore = document.getElementById(&quot;tie-score&quot;);<br>console.log(pScore, cScore, tScore);<br>// new code below<br>pScore.innerHTML = 1;<br>cScore.innerHTML = 4;<br>tScore.innerHTML = 3;</pre><p>I should see the new scores in the document.</p><h4>Images</h4><pre><em>// SCORE ELEMENTS<br></em>const pScore = document.getElementById(&quot;player-score&quot;);<br>const tScore = document.getElementById(&quot;tie-score&quot;);<br>const cScore = document.getElementById(&quot;computer-score&quot;);</pre><pre>// ----- NEW CODE BELOW ----</pre><pre><em>// IMAGE ELEMENTS<br></em>const pImgEl = document.getElementById(&quot;player&quot;);<br>const cImgEl = document.getElementById(&quot;computer&quot;);</pre><pre>console.log(pImg, cImg); // don&#39;t forget to clean up console.logs like this one later! We don&#39;t want to clutter the console!</pre><p>I’ve gone ahead and thrown in my usual console.log of the new variables to be sure I’m grabbing what I think I’m grabbing. Just like with the scores, be sure the “id” attribute of your images is correct. You should be able to change your image with a line like this in the js:</p><pre>pImg.src = &quot;images/paper1.jpg&quot;;</pre><p>You can use a path to a local file or the URL of an image of your choice. Gifs are ok too. Don’t forget to remove the line above, console.logs, and any changes you made to the scores before moving forward.</p><h3>State</h3><h4>Scores</h4><p>I will use an object to create my “library” of RPS images. Each attack holds an array of strings that represents a path to an image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43bdda1ad68f64a5c88b68642712ccd9/href">https://medium.com/media/43bdda1ad68f64a5c88b68642712ccd9/href</a></iframe><p>Now, you should be able to see the image change if you’ve got this in your js:</p><pre>pImg.src = RPSLibrary.scissors[2];<br>cImg.src = RPSLibrary.scissors[3];</pre><pre>pImg.alt = &quot;scissors&quot;;<br>cImg.alt = &quot;scissors; // you can inspect the element to be sure &quot;alt&quot; attribute changed for screen readers</pre><p>Be sure to <strong>test every single image</strong> to catch any typos or broken links/paths.</p><h4>Win Logic Part I</h4><p>We also need to know which weapon defeats which other weapon for later. So, I’m going to expand my library. Instead of each attack holding an array, it will hold an object. So, now we’ve got objects in our object. Can you handle it? YEAH, YOU CAN.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f616c5a71d8e0ae44f1c32655e2adb5/href">https://medium.com/media/1f616c5a71d8e0ae44f1c32655e2adb5/href</a></iframe><p>Notice that we’ll now change an image in the library like this:</p><pre>pImg.src = RPSLibrary.rock.images[3];</pre><p>Be sure to clean up anywhere you’ve console.logged or changed values up to now before continuing.</p><p>Wait, what about that splendid little alt attribute we’re going to change? I never thought you’d ask! Let’s take this Russian nesting doll object to the next level and make each “image” an object in the array that holds the path and the alt:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b185a023760473cd7a0e15bce95eb9a/href">https://medium.com/media/6b185a023760473cd7a0e15bce95eb9a/href</a></iframe><h3>Functions</h3><h4>Select a Random Weapon</h4><p>For our first function, I will need my computer to select an attack. I will use Math.floor() and Math.random() to round off a random number. First I will select a weapon and then an image and assign each to the computer.</p><pre>const randomPicker = () =&gt; {</pre><pre>  const weapon = RPS[Math.floor(Math.random() * 3)]; // selects a weapon at random</pre><pre>  console.log(weapon)<br>  return weapon</pre><pre>};</pre><p>We want to select a random weapon between 0 and 2 (the indexes of RPS) so we’re using JavaScript’s handy <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random</a> function. Math.random will give us a random float (a decimal point) between 0 and 1. It won’t be as big as 1, but it could be as low as 0. Next, we’ll multiply that random decimal point by 3, the number of possible options we’re picking from. That will be wrapped with Math.floor so it rounds down to the nearest whole number. Random numbers are super useful for all kinds of things so this is a great function to remember!</p><p>Go ahead and type randomPicker() right into your console to see it go! Are you getting some random numbers? Cool!</p><h4>Start a Game</h4><p>Now that we have the ability to pick a result, let’s go ahead and start a game. We want to have a <strong>results </strong>variable we can update every round.</p><pre><em>// --- variables ---</em></pre><pre>let results;</pre><p>And we want an init function that instantiates the state of the game right now:</p><pre>function init() {</pre><pre><em>// p is for player c is for computer<br>  </em>results = {<br>    p: &quot;rock&quot;,<br>    c: &quot;rock&quot;<br>  };</pre><pre>}</pre><pre>// don&#39;t forget to call it! <br>init()</pre><p>We’ll continue to update this function throughout the tutorial, but that’s all we need for now. Don’t forget to call the init() function in your JS.</p><h4>Take Turns</h4><p>Now that we’ve started the game, let’s try taking turns. We will need a function go stub these three up in your functions section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a002f8a474df05c3fd96a681223cc303/href">https://medium.com/media/a002f8a474df05c3fd96a681223cc303/href</a></iframe><p>A turn is triggered when the user selects an attack so we will need to listen for clicks with eventListeners:</p><pre><em>/*----- event listeners -----*/<br></em></pre><pre>document.getElementById(&quot;rock-btn&quot;).addEventListener(&quot;click&quot;, handleTurnR);</pre><pre>document.getElementById(&quot;paper-btn&quot;).addEventListener(&quot;click&quot;, handleTurnP);</pre><pre>document.getElementById(&quot;scissors-btn&quot;).addEventListener(&quot;click&quot;, handleTurnS);</pre><p>Click each of your RPS buttons on make sure they all trigger the console log.</p><p>Now, all we need to do is update our results.p to the correct variable in each of the functions we stubbed up earlier:</p><pre>function handleTurnR() {</pre><pre>  results.p = &quot;rock&quot;;</pre><pre>}</pre><pre>function handleTurnP() {</pre><pre>  results.p = &quot;paper&quot;;</pre><pre>}</pre><pre>function handleTurnS() {</pre><pre>  results.p = &quot;scissors&quot;;</pre><pre>}</pre><p>After we’ve set results.p, all of these functions will do the same thing: chose a move for the computer, determine a winner, and display the results of the match so let’s stub up a function where we’ll do that and be sure to call it in each of our handleTurn() functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8b69a73e53c9d814456626b970620ed/href">https://medium.com/media/a8b69a73e53c9d814456626b970620ed/href</a></iframe><p>Now you should get the console log and the results. Notice that results.c doesn’t change yet. Let’s be sure to handle that:</p><pre>function handleResults() {</pre><pre>  results.c = randomPicker();</pre><pre>  console.log(&quot;turn taken!&quot;, results, winner);</pre><pre>}</pre><p>As you click the buttons, you should see your player and computer results update.</p><h4>Determine a Winner</h4><p>In order to determine who our winner is, we’ll want a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Global_scope">global</a> winner variable. Global means it is visible to all other scopes, the same as our results variable.</p><pre><em>// --- variables ---</em></pre><pre>let winner, results;</pre><p>You may or may not want to instantiate the winner with init(), it will be undefined if you do not which is ok. Otherwise, just set it equal to null:</p><pre>function init() {</pre><pre><em>  // p is for player c is for computer</em></pre><pre>  results = {<br>    p: &quot;rock&quot;,<br>    c: &quot;rock&quot;<br>  };</pre><pre>  winner = null; <em>// null -no winner yet; if &#39;p&#39; -player wins; if c -computer wins, if t - tie;</em></pre><pre>}</pre><p>Now that we have a winner, we can write a function to update that variable every round. Let’s stub up our function and think about how it should work:</p><pre>function getWinner() {</pre><pre>  // see if player and computer chose the same thing: that&#39;s a tie<br>  // see if player defeats computer: return player<br>  // only other option is that computer won, sorry player!</pre><pre>}</pre><p>This function needs to look at our player’s choice, compare it to our computer’s choice, and return “tie,” “player,” or “computer” based on our <strong>results</strong>.</p><pre>function getWinner() {</pre><pre><em>  // t for tie, p for player, c for computer<br>  if</em> (results.p === results.c) {<br>    <em>return</em> &quot;t&quot;;<br>  }</pre><pre><em>  // we can also use brackets to access a property in RPSLibrary that we&#39;ll set with a variable</em></pre><pre><em>  if</em> (RPSLibrary[results.p].defeats === results.c) {<br>    <em>return</em> &quot;p&quot;;<br>  }<br><em>  return</em> &quot;c&quot;;</pre><pre>}</pre><blockquote>You Got the Spinnerooni, the Dipsy Doodle and the Sufferin’ Succotash<br>- Dwayne “The Rock” Johnson</blockquote><p>Notice that you don’t see “<em>else</em>” or “<em>if else</em>”, that’s because I just return from the function if I reach an if block so the “<em>else</em>” is implicit! By the time I get to the final return statement, I will always want to return results.c if I haven’t already hit one of the other two blocks so I don’t need an else. This is called <a href="https://www.samanthaming.com/tidbits/23-no-else-return/">No Else Return</a>. Now you should be able to use your console to enter getWinner() and it should return “t” but if you enter results.p = &quot;paper&quot; getWinner() should now return “p” and if you enter results.p = &quot;scissors&quot; getWinner() should return “c”. Make sure that works before continuing. If it doesn’t, check for typos or other errors.</p><p>Let’s update the winner variable back in our handleResults() function:</p><pre>function handleResults() {</pre><pre>  results.c = randomPicker();</pre><pre><em>  // new code below<br>  </em>winner = getWinner();<br>  console.log(&quot;turn taken!&quot;, results, winner);</pre><pre>}</pre><p>Great!</p><h4>Scores</h4><p>Now that we have results, it’s time we started tracking scores. Let’s add scores to our global variables:</p><pre><em>// --- variables ---</em></pre><pre>let winner, results, scores;</pre><p>And our init() function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9a3999db22577014fc5ade5a4c97a59/href">https://medium.com/media/c9a3999db22577014fc5ade5a4c97a59/href</a></iframe><p>Now in handleResults() we want to add one point to the score of the winner with every turn:</p><pre>function handleResults() {</pre><pre>  results.c = randomPicker();<br>  winner = getWinner();</pre><pre><em>  // new code below<br>  </em>scores[winner]++;<br>  console.log(&quot;turn taken!&quot;, results, winner, scores);</pre><pre>}</pre><p>Great! Just one line!</p><p>At this point, we can play the entire game of The Rock, Paper, Scissors from within the console. We can select moves, get results, and keep the scores as our game progresses. At this point, you’ve programmed a fully functioning game.</p><h3>Shine It Up Real Nice…</h3><blockquote>Undertaker with His Mickey Mouse Tattoos and 33-Pound Head<br>-Dwayne “The Rock” Johnson</blockquote><p>Many tutorials can teach you to program this game or one just like it. Perhaps they’ll even do it in fewer lines of code, but too often I see them <strong>fail</strong> to emphasize an approach that defines and manipulates state and before moving on to rendering that state.</p><p>I want to emphasize that our design is <strong><em>data-centric</em></strong>. Many tutorials can teach you to program this game or one just like it, but too often I see them <strong>fail</strong> to emphasize an approach that defines and manipulates state and before moving on to rendering that state. Sometimes they render state as they go, sometimes they don’t, but they do not explain to learners why they’re doing that. This data-centric approach is organized, helps us find flaws in our program, and reduces unnecessary re-rendering.</p><p>Let’s write a render() function that displays the game for the end-user. I’m going to use some comments to define our intentions and a simple console log to verify that it gets called when I want to call it.</p><pre>function render() {</pre><pre><em>  // select random images from our RPS library for p and c<br>  // update scores<br>  // update images<br>  // highlight the winner</em></pre><pre>  console.log(&#39;render working!&#39;)<br>}</pre><p>Let’s be sure to call this function at the end of handleResults():</p><pre>function handleResults() {</pre><pre>  results.c = randomPicker();<br>  winner = getWinner();<br>  scores[winner]++;</pre><pre><em>  // new code below<br>  </em>render();</pre><pre>}</pre><p>The tricky part here is selecting random pictures to display, but fortunately, we already know how to get a random number from our random picker.</p><p>Let’s modify the function we used there to get a random index number from the images section of the RPSLibrary. If this doesn’t make sense at first, it may help to try exporting some values to their own variables. This time, be sure that instead of multiplying by 3, you <strong>multiply by the length of the images array you’ve selected</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21672adec2222b3ef7bb327a52061f60/href">https://medium.com/media/21672adec2222b3ef7bb327a52061f60/href</a></iframe><p>Here’s <strong>the exact same thing</strong>, but with <em>cImgs</em> broken down with more readable variables. I’ll leave it up to you to decide which version you prefer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c5dc0598db7e9590a69d81a530540a3/href">https://medium.com/media/9c5dc0598db7e9590a69d81a530540a3/href</a></iframe><p>Be sure to check your console log for those images. Ok, let’s start updating those DOM elements!</p><p>For our scores, we’ll change them the same way we did at the beginning, but this time we’ll use the values we’re holding in state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bfa21382cc9577302a7ecab40963969/href">https://medium.com/media/7bfa21382cc9577302a7ecab40963969/href</a></iframe><p>Easy! Images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/689cde9f917b80cfe4e690c4269fcee7/href">https://medium.com/media/689cde9f917b80cfe4e690c4269fcee7/href</a></iframe><p>Hey! We’ve basically got a working game already! Let’s add a fun border to the winner to give our user more visual information and use our no else return strategy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d60ced21c76cd0160de50cf9135f9258/href">https://medium.com/media/d60ced21c76cd0160de50cf9135f9258/href</a></iframe><p>All finished! If you enjoyed this tutorial check out my first one, <a href="https://medium.com/javascript-in-plain-english/the-worlds-most-empowering-tic-tac-toe-javascript-tutorial-a889e4c20883">The World’s Most Empowering Tic-Tac-Toe JavaScript Tutorial</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*QquZzp0iIlILsSrNUWOsJA.jpeg" /><figcaption><a href="https://www.flickr.com/photos/151401612@N04/34319038303/in/photolist-UhE3qX-26A3vB4-e3bDNU-e35Y1F-e3bE43-2ecrgiM-2g6jvPk-2hUx9yk-2gNGmUs-2hRGhYr-jqAxV-Mhp16k-o2hQHP-sQAhaj-nK7qza-nZA3F9-o2zXwZ-nK6Asj-nK7kL2-nK7n5p-o2ucjE-o4ngsk-T4MBEE-ntfqY3-6vHSNt-2i5GwGe-e3bF8b-o4nih2-2h6utTp-o2udFs-drxZe5-o2zXqX-9EtLqA-9EqRKB-e4GUBo-e4GoGS-e4GoGQ-e4AMVH-dQT6hK-nK7rDe-25qx8Ad-7m8HKQ-2e744nq-24C5cJV-5GPHHX-P7zKEQ-e3bF3j-e3bDBy-e35X2a-e35WBH">via flickr</a></figcaption></figure><h3>Still hungry for more?</h3><p>Level 2 bonus features you might try adding to this program:</p><ul><li>A countdown timer that runs after the attack move is selected before showing the result</li><li>A sound effect that plays when making a move</li><li>Use 2 ternaries to set the border colors instead of if statements.</li><li>Launch on GitHub pages (or wherever) and send me the link! (Please do this!)</li></ul><h4><strong>JavaScript In Plain English</strong></h4><p>Enjoyed this article? If so, get more similar content by <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>subscribing to our YouTube channel</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee99b7f83e69" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-worlds-easiest-the-rock-themed-rock-paper-scissors-javascript-tutorial-ee99b7f83e69">The World’s Easiest “The Rock” Themed Rock Paper Scissors JavaScript Tutorial</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9 Ways to Get the Least Out of Your Coding Boot Camp]]></title>
            <link>https://medium.com/swlh/9-ways-to-get-the-least-out-of-your-coding-boot-camp-3769967af13?source=rss-afe638e475e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3769967af13</guid>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[bootcamp]]></category>
            <dc:creator><![CDATA[Anna Peterson]]></dc:creator>
            <pubDate>Wed, 25 Dec 2019 07:38:23 GMT</pubDate>
            <atom:updated>2019-12-26T10:00:44.967Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Get the Least Out of Your Coding Boot Camp</h3><p><em>Spend thousands of dollars on a stressful, time-consuming endeavor and walk away with absolutely nothing to show for it like a pro.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6bppbPow8yJfzbVp7zGQg.png" /><figcaption>via Mixkit</figcaption></figure><p>According to Course Report, <a href="https://www.coursereport.com/reports/coding-bootcamp-job-placement-2017">outcomes for most boot camp</a> grads look good. In 2017, we experienced an average 51% salary increase and 80% of us obtained employment using the skills we learned. Low-income students particularly stood to gain, they reported <strong>doubling</strong> their previous salary after completing a boot camp. So, how do you beat the odds?</p><h4>1. No Research? No Problem!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFG1UnM2JgWbmiCFJGUDoQ.png" /><figcaption>via Mixkit</figcaption></figure><p>The other day I took an Uber. My driver, a young guy confident enough to openly listen to U2, told me he planned to enroll in a boot camp. The way he talked about it was as if he planned to stop by Certificate Depot and pick up his Web Developer certification then head over to the MongoDB headquarters and exchange it for a job where he told me he planned to be offered $90k starting and pay the whole thing off in a few months. I gently attempted to tell him that’s a little higher than average for our city and it does take some time and effort to get a job offer, but the guy driving me to Starbucks knew far more than I do about this thing I did. Meanwhile, my phone buzzed with messages from a fellow alumn who was processing rejection number 142 on his 5th month of job hunting.</p><p>As promising as the stats are, there’s also reason to believe the numbers reported by boot camps <a href="https://techbeacon.com/app-dev-testing/bootcamps-wont-make-you-coder-heres-what-will">can be misleading</a>. It might be easy to attend one of the many local meetups, classes, workshops, open houses, or networking events full of boot camp grads and students who could give you intel on the teachers, courses, and outcomes in your area.</p><p>You could look for your prospective school on <a href="https://www.reddit.com/r/Austin/comments/db32bp/coding_bootcamps_in_austin/">Reddit</a>, <a href="https://www.coursereport.com/">Course Report</a>, or even <a href="https://www.quora.com/Has-anyone-gotten-a-job-thanks-to-General-Assemblys-Web-Dev-Immersive-Program-Are-there-good-alternatives-outside-of-the-USA">go ask about it</a>, but that might lead you to discover <a href="https://blog.codinghorror.com/please-dont-learn-to-code/">glaring</a> <a href="https://hackernoon.com/confessions-of-a-bootcamp-graduate-hack-reactor-f921c441fb23#.1qq1yygn3">shortcomings</a>, horror stories, or even <strong>strategies for success in the program of your choice</strong>.</p><p>Who needs that? You’ve got your gut instinct, a suspiciously simple 5-minute “entrance exam”, and a recruiter who tells you nothing but good things about this program! What more do you need? Send them some money already! And DON’T ask about discounted tuition or a scholarship, even if you could use it!</p><h4>2. Don’t prepare, Think Magically Instead</h4><p>My school, like many others, provided prework assignments. I had no idea you could just blow this off, but it turns out that’s exactly what some learners do.</p><p>If you prepare at all, try to blow through everything in one glorious burst. <a href="https://en.wikipedia.org/wiki/Pomodoro_Technique"><strong>Pomodoro technique be damned</strong></a><strong>!</strong></p><p>Waiting, sometimes called procrastination, will create “pressure” and pressure is <strong>magic</strong>. It will magically make you much faster than everybody else. It will magically mean you only need about half the time to complete your assignments. That doesn’t make sense, but that won’t stop us!</p><p>Remember that one time in college when you stayed up all night writing that essay and you got a B+? Or maybe it was a B-? Well, this is just like that. Focus on completing things last minute. Definitely don’t learn a little more than that, either. A <a href="https://www.freecodecamp.org/">Free Code Camp</a> course on JavaScript would be a cheap way to get yourself started and doesn’t take long, but we’ve established that you’re too magical for preparation.</p><p>Don’t bother with any kind of <strong>financial</strong> preparation, either. That Uber driver said it’s ok.</p><h4>3. It’s Not What You Do, It’s The Way You Do It</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PASaEyUBK_r4OSgwnlwecw.png" /><figcaption>via Mixkit</figcaption></figure><p>So, you’re finally in class! Congrats! You’d think it would go without saying that since you’ve committed to this life-altering experience, you would at least <strong>do the work</strong>. Nope. While I was in boot camp, a classmate just didn’t do <em>any</em> assignments. He was kicked out <strong>and you can be too!</strong></p><p>What’s that, you say? You’re planning to do assignments? Well, if you must, be sure to get <strong>emotionally unraveled</strong> every time you hit a wall. You’ll hit walls often because you’re doing something challenging and new so you’ll need to have a not-coping strategy. Beat yourself up. Think things like, <em>I guess I just can’t do this</em>, <em>this is way too hard for me</em>, <em>this is not fair</em>, and <em>no one believes in me</em>! Those are the thoughts that will eat away at your remaining shreds of confidence. Feed them. At all costs avoid thinking, <em>I can do this</em>, <em>I just need to keep trying</em>, <em>struggling is perfectly normal and even good</em>, or<em> I love a challenge, bring it on!</em> With the right mentality, you can kill your resolve and spend a lot of time not coding. Scrunch your nose up at the thought of JavaScript. Be joyless and complain frequently about this opportunity you spent months saving up for.</p><h4>4. Be Proud</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75Up8IsuvN5rfI7EDfgN6Q.png" /><figcaption>via Mixkit</figcaption></figure><p>This might be a surprising way to get the least out of your boot camp, but hear me out. This is the kind of proud that goes beyond acknowledging the effort and guts it took to even enroll in your boot camp, this should <strong>spill all the way over into arrogance</strong>. <em>Refuse</em> to be humble.</p><p>Pride’s got to come way before learning. Let your pride prevent you from asking for help. You’d think it would be perfectly ok for people in a professional development program to ask questions and admit to not knowing something, why else would you be there except because you <em>don’t</em> know something?</p><p>Here’s why: <em>you</em> only took this course to get <strong>formal</strong> recognition of your programming skills. Unlike seasoned professionals, you’ve learned everything there is to know about coding. The instructors have nothing useful to say, the boot camp is just there to print a piece of paper for you. You can get the least out of this experience by talking over instructors, ignoring them, and playing around on the internet throughout the class so everyone <em>else</em> knows how worthless this experience is for you too.</p><p>If you can’t write rock-paper-scissors in JavaScript, that’s only because it’s <em>so </em>beneath you. You should be writing chess instead. If you can admit the former bartender who never even took half a Udemy course on ethical hacking might<em> grasp SQL better than you do</em>, you might as well forget all about getting the least out of your boot camp. Pride might come more easily to guys reading this on an Opera browser, but just about anyone can refuse to take direction, not ask questions, and generally be unteachable.<strong> I have faith in you!</strong></p><h4>5. Ctrl C + Ctrl V</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*sB9Lh-DP2HlygzjEu-671g.png" /></figure><p>Every programmer copies and pastes. We do it <em>all the time</em>. One classmate joked, “I don’t know about coding, but my copy and paste game is on point!” You’ll use tools like Bootstrap and Materialize that <em>require</em> a lot of copy + paste. What will mark you as someone who isn’t getting much out of your boot camp is outright plagiarism. When you care more about <em>seeming</em> like you get it than actually getting it, you’re on the right track.</p><h4>6. Play Poorly With Others</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVS03TVuk83My3PTrOobUA.png" /><figcaption>via Mixkit</figcaption></figure><p>Unless you have a job lined up when you graduate, your class is probably the first professional network you’ll have in this industry. Aside from the skills I acquired, the most important thing I graduated with was a <strong>network</strong>. That network led to my job and has been there for me ever since. My network got drinks last week. They work for companies like Keller-Williams, Cloudflare, Adobe, and IBM. To get the least out of your experience, be the one person everyone can count on to talk down to them, make offensive remarks, and be difficult.</p><p>There are less obvious ways of playing poorly, too. For example, not taking time to develop relationships at all or not adding value in group projects.</p><p>So, ignore your soft skills and assume your hard skills will be enough to carry you, even though over <a href="https://www.coursereport.com/reports/2018-coding-bootcamp-market-size-research"><strong>20,000 other people</strong></a> will graduate boot camps this year with the <strong>exact same set of hard skills</strong>. Every tech recruiter’s dream candidate is a crotchety hot-head with a rudimentary understanding of JavaScript, right?</p><h4>7. No Self-Care, No Sleep, No Time Off</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73tu48a_oPqTgnADIVztRQ.png" /><figcaption>via Mixkit</figcaption></figure><p>You’re inspired by Bill Gates’s stories about being sleep deprived and under-fed during the early years of Microsoft so you’ve decided to follow his model for success. Way to go! It shouldn’t matter that <a href="https://www.forbes.com/sites/alicegwalton/2015/11/13/the-sleep-habits-of-highly-successful-people-infographic/#6609dbed6d7f">most highly successful people sleep more than 6 hours per night</a> and even <a href="https://www.cnbc.com/2019/12/18/microsoft-co-founder-bill-gates-once-thought-sleeping-a-lot-was-lazy.html">Bill admits it made him less effective</a>.</p><p><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5831725/">Sleep aids in cognition and memory formation</a> so practice poor sleep hygiene. With a little sleep deprivation, even if you manage to stay awake throughout your lessons, you won’t remember them anyway!</p><p>A good coding boot camp is very challenging so it should be easy to neglect your mental health and allot yourself insufficient time <em>away</em> from your computer screen to digest information (and food).</p><p>Self-care is challenging, boot camps are challenging, and while you can still get a lot out of your boot camp while attending to other responsibilities,<strong> you just won’t get as much out of this experience as long as you’re burning the candle at both ends</strong>. This isn’t fair. Parents, people with mental health challenges, and those who experience some sort of unforeseen crisis in the course of their study are fighting an uphill battle in the mud on a rainy day wearing stilettos. If you find yourself fighting this battle, don’t talk to school administrators to find a solution such as deferring and completing the rest of your program remotely. Don’t tell people in your life that you need help, and don’t give yourself a break for a day. Don’t cut yourself some slack.</p><h4>8. When It’s Over, It’s Over</h4><p>Here’s what a successful boot camp graduate’s GitHub contributions look like 6 months after graduation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tp1S_UWEO82Wi3HJZ6Z4_Q.png" /><figcaption>Github contributions for a successful graduate, very green</figcaption></figure><p>This guy got competing job offers and was quickly hired into a well-known company. I can see a story in this image about dedication and persistence. He codes every day. That’s impressive.</p><p>Here’s another grad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZ9G1H0hhh_0abRhf9vWJw.png" /><figcaption>GitHub contributions for a classmate</figcaption></figure><p>What story does this image tell? GitHub contributions don’t tell us everything, but if you were hiring which candidate would you choose? Get the least out of your coding boot camp: stop learning the day you graduate. Don’t code and you won’t discover the joy in coding that will motivate you to keep doing it.</p><p>If “developer” is just a word on your resume rather than a practice, then you’ve successfully wasted 14 weeks. Congrats!</p><h4>9. Don’t Go</h4><p>Boot camps are, after all, pretty useful learning experiences even when you’re just paying a lot of money to find out coding isn’t really for you. That’s useful, right? Boot camps also stretch learners and introduce them to people from all kinds of backgrounds. If all else fails, just don’t show up. The safest way to get nothing out of a boot camp is to stay safely at home and never try in the first place. If you’ve already made the blunder of trying, you can always give up and stop going any day!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2h97QWb9P9vUr-L3Fz_qHQ.png" /><figcaption>via Mixkit</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3769967af13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/9-ways-to-get-the-least-out-of-your-coding-boot-camp-3769967af13">9 Ways to Get the Least Out of Your Coding Boot Camp</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[What’s the point of GoLang Pointers? Everything you need to know!]]></title>
            <link>https://medium.com/@annapeterson89/whats-the-point-of-golang-pointers-everything-you-need-to-know-ac5e40581d4d?source=rss-afe638e475e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac5e40581d4d</guid>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[go-programming-language]]></category>
            <category><![CDATA[go-programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anna Peterson]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 17:37:22 GMT</pubDate>
            <atom:updated>2019-11-19T17:31:00.206Z</atom:updated>
            <content:encoded><![CDATA[<p>“Go has pointers. A pointer holds the memory address of a value.” <strong>BUT WHY?!</strong></p><p>Even after reading the paragraph on pointers in <a href="https://tour.golang.org/moretypes/1"><em>A Tour of Go</em></a>, the usefulness and implementation of pointers might seem unclear. In the following article, I will explain the point of pointers and you will emerge with both a theoretical and practical command of Go pointers! Both are important for mastering GoLang!</p><h4>What Developers Get Wrong About Pointers</h4><ul><li>They are not specific. Developers might say, “Use a pointer” to mean similar but different things.</li><li>They call both &amp;myVar and *myVar pointers, leaving newcomers confused.</li><li>They refer to an underlying value as the pointer itself.</li><li>They falsely believe that the zero value of a pointer is the zero value of the pointer’s type.</li></ul><p>Unfortunately, this muddies the waters for newbies because *myVar is a pointer to myVar’s value and &amp;myVar generates a pointer to the memory address of myVar.</p><p>Some developers use pointers pretty effectively, but they can’t explain their usage to peers. Or, as was my case, developers <em>theoretically</em> understand what pointers are, but don’t know when to use them. Wherever you’re at, I’ll get you up to speed!</p><h4>So what are pointers, really?</h4><p>A pointer is simply <strong>a variable containing the address of another variable</strong>.</p><p>Every variable has a location in memory. When we generate a pointer with the &amp; operator, we are accessing the location where its operand is stored in memory. The * operator allows us to access the values held at a location in memory. Think of a book. The &amp; operator would generate a page number, the * operator would tell you what’s on a given page number.</p><p>We could also think of a pointer as a trail that guides our program to a value. We get a signpost showing us where the trail is (*) and a signpost maker (&amp;). I like this analogy because you can think of a little pointing arrow sign every time you see *T or creating an arrow sign every time you see &amp;T.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*a9kRljrF6Oj-gnFmx_78eQ.jpeg" /><figcaption>Pointer signs photo courtesy of FreePik.com</figcaption></figure><p>Via <a href="https://tour.golang.org/moretypes/1">A Tour of Go</a>:</p><p>*:</p><blockquote>The type *T is a pointer to a T value. Its zero value is nil.</blockquote><p>&amp;:</p><blockquote>The &amp; operator generates a pointer to its operand.</blockquote><p>Try this code on the <a href="https://play.golang.org/">go playground</a> or in your code editor to warm up(<strong>type it out yourself</strong> for best results! Don’t be lazy!):</p><pre>package main</pre><pre>import (<br> &quot;fmt&quot;<br>)</pre><pre>func noPointer() string {<br> return &quot;string&quot;<br>}<br>func pointerTest() *string {<br> return nil // You cannot return nil from a function that returns a string<br> // but you can return nil from a function that returns a pointer to a string!<br> // The zero value of a pointer is nil<br>}<br>func pointerTestTwo() *string {<br> s := &quot;string&quot; // &amp;&quot;string&quot; doesn&#39;t work<br> return &amp;s<br>}<br>func main() {<br> fmt.Println(noPointer())      // prints string<br> fmt.Println(pointerTest())    // prints &lt;nil&gt;<br> fmt.Println(pointerTestTwo()) // prints something like 0x40c158 (an address in memory)</pre><pre>s := pointerTestTwo() // now s holds an address in memory for a variable<br> fmt.Println(s)        // something like 0x40c138<br> sp := *s              // now sp holds the value found at the address s holds</pre><pre>fmt.Println(sp) // string</pre><pre>}</pre><p><a href="https://play.golang.org/p/07dPsEF4YHX">Run this code</a></p><p>So, now we know what a pointer is and we even got to see what an address in memory looks like! Let’s dive a little deeper!</p><h4>Why do we need pointers?</h4><p>For those coming from languages like JavaScript, it can be difficult to understand why you would ever need a pointer. Don’t we always want to work with the underlying value and not the address where it’s held in memory? What are we going to do with that?</p><p>In the 1960s, pointers gave programmers a way to pass a variable’s memory location and then <strong>dereference</strong> it for manipulation as needed. This provided a way of creating more complex data structures while still consuming less memory. Harold Lawson is credited with inventing pointers. He wrote a seminal paper on the topic called, <em>PL/I List Processing </em>(see more resources at the end)<em>.</em></p><p>Instead of copying a large amount of data every time you need to pass it, programmers could pass its address. Going back to the book analogy, it’s easier to pass a function a page number than an entire page.</p><p>It’s not the 1960s anymore, but we’re still concerned with effective memory usage and efficiency. Go was written to be a very sleek language so it makes sense that it allows programmers to pass information this way. Still, GoLang could do this work behind the scenes and make it look like it isn’t, right?</p><p>In Go, everything is <strong>passed by value</strong>. Every time you pass something to a function, the function gets a value, but it doesn’t have access to the original object. See what I mean by <strong>typing the following code</strong> <strong>out</strong> in the Go playground!</p><pre>package main</pre><pre>import (<br> &quot;fmt&quot;<br>)</pre><pre>type User struct {<br> Name string<br> Pets []string<br>}</pre><pre>func (u User) newPet() {<br> u.Pets = append(u.Pets, &quot;Lucy&quot;)<br> fmt.Println(u)<br>}<br>func main() {<br> u := User{Name: &quot;Anna&quot;, Pets: []string{&quot;Bailey&quot;}}<br> u.newPet()     // {Anna [Bailey Lucy]} -- the user with a new pet, Lucy!<br> fmt.Println(u) // Hey, wait! Where did Lucy go?<br>}</pre><p><a href="https://play.golang.org/p/b1bzQRkLjHs">Run in the Go Playground</a></p><p>Here, I created a function to give a user a new pet, “Lucy” and I created a user, “Anna”.</p><p>Lucy was successfully appended to Anna’s pets in the newPet() function, but when we printed the user on the following line, she didn’t have her new pet!</p><p>I passed a <strong>value</strong> of a user to newPet() and gave <em>her</em> a new pet. We still haven’t changed (or <strong>mutated</strong>) the original user. If we go back to our code, we could write it like this:</p><pre>func (u2 User) newPet() {<br> u2.Pets = append(u2.Pets, &quot;Lucy&quot;) <br> fmt.Println(u2) // {Anna [Bailey Lucy]} -- user with a new pet, Lucy, but this user is not the same as the one in main()! <br>}</pre><pre>func main() {</pre><pre>u := User{Name: &quot;Anna&quot;, Pets: []string{&quot;Bailey&quot;}}<br> u.newPet() <br> fmt.Println(u) // The user still has one pet. </pre><pre>}</pre><p>Now try this:</p><pre>package main</pre><pre>import (<br> &quot;fmt&quot;<br>)</pre><pre>type User struct {<br> Name string<br> Pet  []string<br>}</pre><pre>func (p2 *User) newPet() {<br> fmt.Println(*p2, &quot;underlying value of p2 before&quot;)<br> p2.Pet = append(p2.Pet, &quot;Lucy&quot;)<br> fmt.Println(*p2, &quot;underlying value of p2 after&quot;)<br>}</pre><pre>func main() {</pre><pre>u := User{Name: &quot;Anna&quot;, Pet: []string{&quot;Bailey&quot;}} // this time we&#39;ll generate a pointer!<br> fmt.Println(u, &quot;u before&quot;)</pre><pre>p := &amp;u // Let&#39;s make a pointer to u!</pre><pre>p.newPet()<br> fmt.Println(u, &quot;u after&quot;)</pre><pre>// Does Anna have a new pet now? Yes!<br>}</pre><p><a href="https://play.golang.org/p/uUNrcfM8mDb">Run this code in the Go playground</a></p><p>With pointers, we’re passing a memory address of a user to newPet() and changing the user rather than a copy of the user.</p><p>Pointers provide <strong>shared access</strong> to a value. Pointers can help us avoid unintentionally changing data by being intentional about declaring shared access!</p><p>If someone asks you why pointers are used in Go, you can now tell them,</p><blockquote>“Pointers are used for efficiency because everything in Go is passed by value so they let us pass an address where data is held instead of passing the data’s value, to avoid unintentionally changing data, and so we can access an actual value in another function and not just a copy of it when we want to mutate it.”</blockquote><h4>Some Usage Guidelines</h4><p>What does this tell us about how to use pointers?</p><ul><li><strong>If we want a method to modify its receiver, we <em>must</em> use a pointer!</strong></li><li>If we have a <strong>very large</strong> amount of data, we can pass the value of a reference to its location for better performance.</li><li>If we <strong>do not </strong>want to alter some data, the value of the receiver can be passed instead of a pointer to its receiver — as in our first example with newPet(). In this case, the receiver is <strong>treated more like an argument</strong>.</li><li>The <strong>main<em> </em></strong>reason to use (or not use) pointers should be determined by access and how we want to use it!</li></ul><h4>Pointers: Concurrency</h4><p><strong>Pointers are not safe for concurrent access. </strong>When you use multiple threads, you will get inconsistent results if you are changing and reading data from the same places in memory. Be sure to <strong>limit access </strong>and <strong>pass values</strong> when necessary to reduce panics and unpredictable behavior. Avoid pointers in your Go routines.</p><h3>Conclusions</h3><p>I hope you enjoyed this discussion of GoLang pointers. If you have any questions or if I missed something, please let me know in the comments! Thanks!</p><h3>More Resources</h3><h4>Pointers in GO</h4><ul><li><a href="https://golang.org/doc/effective_go.html#pointers_vs_values">Effective Go: Pointers vs. Values</a></li><li><a href="https://www.youtube.com/watch?v=1YEufRd3_Fk">Video: When to Use Pointers by Learn To Code</a></li><li><a href="https://www.golang-book.com/books/intro/8">An Introduction To Programming In Go: Pointers</a></li></ul><h4>Pointers in Computer Science</h4><ul><li><a href="https://www.researchgate.net/publication/220424487_PLI_list_processing">Free Download of PL/I List Processing</a></li><li><a href="https://en.wikipedia.org/wiki/Pointer_(computer_programming)#History">Wikipedia: Pointers in Computer Programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac5e40581d4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[addEventListener vs onclick: Which one should you draft into your fantasy football team?]]></title>
            <link>https://medium.com/@annapeterson89/addeventlistener-vs-onclick-which-one-should-you-draft-into-your-fantasy-football-team-16ea9ae71ee0?source=rss-afe638e475e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/16ea9ae71ee0</guid>
            <category><![CDATA[comedy]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Anna Peterson]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 04:27:07 GMT</pubDate>
            <atom:updated>2019-11-04T04:27:07.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="a lady wizard riding a unicorn and holding a football with text fantasy football" src="https://cdn-images-1.medium.com/max/750/1*U9UOFggVjG5YSZEEnKOfSQ.jpeg" /><figcaption>Anyone else imagining wizards on unicorns tossing the ol’ pigskin every time they hear the words ‘fantasy football’?</figcaption></figure><p><em>target.addEventListener(‘click’, myFunction)</em> OR <em>onclick=“(myFunction)”</em>? Which one should I use? And which one of them could be a sleeper? — That’s fantasy football lingo for a secretly good player.</p><p>Time to learn about event objects!</p><p>onclick is a property of the GlobalEventHandlers mixin. It processes click events on an element. onclick is also an HTML event attribute that can call a function without the need for script tags.</p><p>We like to keep languages separate, we like to keep the behavior side of things in our JavaScript, and the structural or presentational elements in our HTML. With the GlobalEventHandlers mixin we can still use target.onclick right in our JS, though. That just about levels the playing field, right? What’s more, the <a href="https://www.w3schools.com/jsref/met_element_addeventlistener.asp">addEventListener()</a> method is not supported in Internet Explorer 8 and earlier versions. Looks good for onclick so far.</p><blockquote>Let’s be real though, who cares about people still using Internet Explorer 8? Even Microsoft itself no longer provides support for that thing. People who use IE8 are wrong, not developers who use addEventListener.</blockquote><p><em>Here’s</em> where we see behavioral differences:</p><p>JS:</p><pre>const first = document.getElementById(&quot;first&quot;);<br>const second = document.getElementById(&quot;second&quot;);</pre><pre>function handler1() {<br>  alert(&quot;First handler&quot;);<br>}</pre><pre>function handler2() {<br>  alert(&quot;Second handler&quot;);<br>}</pre><pre>first.addEventListener(&quot;click&quot;, handler1);<br>first.addEventListener(&quot;click&quot;, handler2);</pre><pre>second.onclick = handler1;<br>second.onclick = handler2;</pre><p>HTML:</p><pre>&lt;div id=&quot;first&quot;&gt;First Element&lt;/div&gt;<br>&lt;div id=&quot;second&quot;&gt;Second Element&lt;/div&gt;</pre><p>Clicking “<em>First Element”</em> will trigger 2 alerts. Clicking on “<em>Second Element”</em> will trigger only the second alert! <strong>With addEventListener, you can attach multiple events to the same element, but not with onclick.</strong></p><blockquote>Quick note: For accessibility reasons, it’s best practice to include a keydown event in addition to a click event.</blockquote><p>BUT WAIT, there’s <em>more </em>to learn from addEventListener. Have you ever looked at the optional third argument addEventListener takes?</p><p>If you have 3 elements with element 3 nested inside element 2 nested inside element 1, and functions called handler1, handler2, and handler3 attached to the corresponding elements what order will they trigger in? (see diagram)</p><figure><img alt="a diagram showing 3 concentric rectangles: div, span, button, and an arrow pointing out: event bubbling" src="https://cdn-images-1.medium.com/max/371/1*ZIZgDPvFv2K0zXWFCeidoA.jpeg" /><figcaption>event bubbling via Wikipedia</figcaption></figure><p>That all depends on how the event <em>propagates</em>. No matter where you put your handler, the most nested element is considered the target. The element where the event originated is called the currentTarget.</p><p>You can see how event bubbling and capturing work on nested elements and propagate through the DOM tree <a href="https://repl.it/@annaelizabeth20/eventListener-v-onclick">with this repl</a>. Due to repl.it’s way of logging console.time(), you can get the most accurate results by copying and pasting the code into a local file and testing it in your browser.</p><p>Our event passes through three phases:</p><blockquote>The <strong>capture phase</strong>: The event object propagates through the target’s ancestors from the <a href="https://www.w3.org/TR/DOM-Level-3-Events/#window">Window</a> to the target’s parent. This phase is also known as the <em>capturing phase</em>.</blockquote><blockquote>The <strong>target phase</strong>: The event object arrives at the event object’s <a href="https://www.w3.org/TR/DOM-Level-3-Events/#event-target">event target</a>. This phase is also known as the <em>at-target phase</em>. If the <a href="https://www.w3.org/TR/DOM-Level-3-Events/#event-type">event type</a> indicates that the event doesn’t bubble, then the event object will halt after completion of this phase.</blockquote><blockquote>The <strong>bubble phase</strong>: The event object propagates through the target’s ancestors in reverse order, starting with the target’s parent and ending with the <a href="https://www.w3.org/TR/DOM-Level-3-Events/#window">Window</a>. This phase is also known as the <em>bubbling phase</em>.</blockquote><p>-<a href="https://www.w3.org/TR/DOM-Level-3-Events/#event-flow">w3.org documentation</a></p><p><em>These also happen to be the phases of a quarantine.</em></p><p>The events that bubble will trigger like this: <strong>handler3 → handler2 → handler1</strong>. The outermost element’s handler triggers last. Events with useCapture: true? They will go in the opposite order. onclick will always default to <strong>false</strong> for that third argument. There are limited use cases for using that argument and most of them wouldn’t apply to a ‘click’ event, but it can prepare or prevent behavior that will later be applied by event delegation during the bubbling phase.</p><h3>React</h3><p>While this takes us outside the scope of vanilla JS and HTML, JSX <a href="https://reactjs.org/docs/handling-events.html">handles events</a> differently and eschews event listeners almost entirely. Because React is so popular, it doesn’t hurt to be familiar with the HTML inline onclick syntax (note that JSX uses camelCase rather than lower case so it becomes onClick). Similarly, jQuery events do not use capture in most cases and onclick will work just fine for attaching a single click event succinctly. This makes onclick the sleeper that you may want on your fantasy football team.</p><p>At the end of the day, what’s most important is <strong>which game you’re playing</strong>. Remember that football can mean different things in different contexts (such as the U.S.A. vs almost everywhere else). So, understand which player is going to be most successful in each context. More importantly, think about how events propagate and trigger in the DOM tree. I’d pick addEventListener in vanilla JS because it’s more robust and generally preferred, but onclick works just fine most of the time and becomes especially useful when introducing React. This metaphor’s stretching like Mister Fantastic so let’s just read some documentation and relax!</p><h4>onclick</h4><blockquote>The <strong>onclick</strong> property of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers">GlobalEventHandlers</a> mixin is the <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventHandler">EventHandler</a> for processing <a href="https://developer.mozilla.org/en-US/docs/Web/Events/click">click</a> events on a given element.</blockquote><blockquote>The click event is raised when the user clicks on an element. It fires after the <a href="https://developer.mozilla.org/en-US/docs/Web/Events/mousedown">mousedown</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/Events/mouseup">mouseup</a> events, in that order.</blockquote><p>— <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick">MDN</a></p><h4>addEventListener</h4><blockquote>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget">EventTarget</a> method <strong>addEventListener()</strong> sets up a function that will be called whenever the specified event is delivered to the target. Common targets are <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Element</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document">Document</a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">Window</a>, but the target may be any object that supports events (such as <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a>).</blockquote><blockquote>addEventListener() works by adding a function or an object that implements <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventListener">EventListener</a> to the list of event listeners for the specified event type on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget">EventTarget</a> on which it&#39;s called.</blockquote><p>— <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">MDN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16ea9ae71ee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The World’s Most Empowering Tic-Tac-Toe JavaScript Tutorial]]></title>
            <link>https://javascript.plainenglish.io/the-worlds-most-empowering-tic-tac-toe-javascript-tutorial-a889e4c20883?source=rss-afe638e475e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a889e4c20883</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[humor]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anna Peterson]]></dc:creator>
            <pubDate>Wed, 01 May 2019 23:26:19 GMT</pubDate>
            <atom:updated>2020-04-12T22:01:16.602Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tic-Tac-Toe is a great starter project for any new programmer!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EwpvDBIfjJiPH100l51UGg.png" /></figure><p>This tutorial is meant for absolute beginners. I’ve included links to documentation. Please look it over. This tutorial is 100% vanilla JavaScript with minimal CSS and HTML. Take your time and let me know how it works out.</p><p>EDIT: If you get <em>really</em> stuck, here’s the completed code: <a href="https://github.com/annaelizabeth2019/tictactoetwo">https://github.com/annaelizabeth2019/tictactoetwo</a></p><p><strong>You will need:</strong></p><ul><li>VS Code</li><li>The internet (and since you’re reading an online tutorial, you’re halfway there! Way to go!)</li></ul><h3><strong>Getting Started</strong></h3><p>Start by creating a directory in your computer titled, <em>Cheryl’s Tic-Tac-Toe</em> and create these child directories: <em>js</em>, <em>css</em>; and these three files: <em>index.html</em>, <em>css/style.css</em>, and <em>js/main.js</em>.</p><p><strong>Review the basics:</strong></p><p>Always start any programming task by clarifying what you want to do and then breaking it down into small steps. Small steps can get you just about anywhere if you’ve got enough time. If you get stuck, break it down smaller, girl!</p><p>Tic-Tac-Toe is a <strong>two-player game</strong> played on <strong>a 3 x 3 grid. </strong>Players <strong>take turns</strong>. One <strong>marks “X”</strong> and the other <strong>“O”</strong>. A <strong>winner</strong> is declared when one player can <strong>align 3 of their markings in a row, in a column, or diagonally</strong>. In the event that there are no longer available spaces and no one has won, <strong>a tie</strong> is declared. Broken down, this is our game plan:</p><ul><li>3 x 3 grid</li><li>Make Your Mark</li><li>Take Turns</li><li>“X” and “O”</li><li>Win Logic: align 3 in a row, in a column, or diagonally</li><li>Declare a Tie</li><li>The Game is Finished</li></ul><h3><strong>3 x 3 Grid</strong></h3><p>Ahh, the foundation of our game!</p><p>Make an HTML boilerplate by typing ! <em>+ enter </em>if you’re in VS Code (which you are because I told you to be and we can’t do this tutorial if we can’t trust each other, now can we?)</p><p>Link up your CSS and JavaScript by including them in the head of the HTML:</p><pre>&lt;head&gt;</pre><pre>&lt;meta <em>charset</em>=&quot;UTF-8&quot;&gt;</pre><pre>&lt;meta <em>name</em>=&quot;viewport&quot; <em>content</em>=&quot;width=device-width, initial-scale=1.0&quot;&gt;</pre><pre>&lt;meta <em>http-equiv</em>=&quot;X-UA-Compatible&quot; <em>content</em>=&quot;ie=edge&quot;&gt;</pre><pre>&lt;!-- this is how we link up the stylesheet --&gt;</pre><pre>&lt;link <em>href</em>=&quot;css/style.css&quot; <em>rel</em>=&quot;stylesheet&quot; <em>type</em>=&quot;text/css&quot;&gt;</pre><pre><em>&lt;!-- And this is how we link up the JS! --&gt;</em></pre><pre>&lt;script <em>defer</em> <em>src</em>=&quot;js/main.js&quot;&gt;&lt;/script&gt;</pre><pre><em>&lt;!-- Be sure to give your game a fun title --&gt;</em></pre><pre>&lt;title&gt;Empowering Tic Tac Toe for the Good of Humanity&lt;/title&gt;</pre><pre>&lt;/head&gt;</pre><p>A note on that defer in the &lt;script&gt; tag: the word <em>defer</em> will tell the browser to <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script">wait to execute</a> that JS block until the DOM is fully parsed. This way, it can safely be included at the top of our HTML document.</p><p><strong>I am Your Console AMA: </strong>Test that your <em>main.js </em>is linked up by writing this line of code in <em>main.js</em>:</p><pre>console.log(&#39;Your JS is linked up. Be the person you needed when you were little.&#39;)</pre><p>If you open a live server of the document and check your <a href="https://developers.google.com/web/tools/chrome-devtools/">dev tools</a>, you should see your message in the console.</p><p>Back in the &lt;body&gt; of <em>index.html</em>:</p><pre>&lt;h1&gt;Tic-Tac-Toe&lt;/h1&gt;</pre><pre>&lt;h2&gt;It&#39;s X&#39;s turn!&lt;/h2&gt;</pre><pre><em>&lt;!-- Many websites are just divs on divs on divs. Pay attention to the class and id attributes. We will be using those later to style and find elements in the document --&gt;</em></pre><pre>&lt;div <em>class</em>=&quot;flex-container flex-column&quot;&gt;</pre><pre>&lt;div <em>class</em>=&quot;flex-container flex-wrap&quot; <em>id</em>=&quot;board&quot;&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div <em>class</em>=&quot;square&quot;&gt;&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre><em>&lt;!-- A reset button because users are going to want to play round after round of your glorious game without ever refreshing the browser! --&gt;</em></pre><pre>&lt;button <em>id</em>=&quot;reset-button&quot;&gt;reset&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><p>Many programmers are loathe to write CSS. Many would have us believe that’s because they are serious programmers who don’t want to waste time on CSS fluff, however, my dear Cheryl or Larry or whoever you may be, YOU are secure in your abilities and you know that presentation is a big part of the experience of your product. So, I’m going to provide some <strong>basic</strong> styling, but you aren’t going to be afraid to make it your own! Go on! Make it shine, Cheryl!</p><p>in <em>css/style.css</em>:</p><pre>body {</pre><pre>text-align: center;</pre><pre>font-family: Arial, Helvetica, sans-serif;</pre><pre>}</pre><pre>h2 {</pre><pre>margin: 0 auto;</pre><pre>font-size: 35px;</pre><pre>margin: 10px;</pre><pre>}</pre><pre><em>.flex-container</em> {</pre><pre><em>/* In order to use flex-box we need to first set our display property */</em></pre><pre>display: flex;</pre><pre><em>/* center the container horizontally */</em></pre><pre>justify-content: center;</pre><pre><em>/* this will center content vertically */</em></pre><pre>align-items: center;</pre><pre><em>/* tells the container to align the children in columns rather than rows */</em></pre><pre>}</pre><pre><em>.flex-column</em> {</pre><pre>height: 100%;</pre><pre>width: 100%;</pre><pre>flex-direction: column;</pre><pre>}</pre><pre><em>.flex-wrap</em> {</pre><pre><em>/* tells the container to drop down once it reaches max-width */</em></pre><pre>flex-wrap: wrap;</pre><pre>height: 432px;</pre><pre>width: 432px;</pre><pre>}</pre><pre><em>.square</em> {</pre><pre>border: 2px solid rgba(0, 0, 0, .75);</pre><pre>height: 140px;</pre><pre>width: 140px;</pre><pre>}</pre><pre><em>#reset-button</em> {</pre><pre>text-align: center;</pre><pre>font-size: 20px;</pre><pre>border: 1px solid black;</pre><pre>height: 55px;</pre><pre>width: 100px;</pre><pre>margin: 10px;</pre><pre>}</pre><p>If you haven’t worked with flex-box, know that it is a powerful tool for layout. Another great option is the CSS <a href="https://css-tricks.com/snippets/css/complete-guide-grid/">grid</a>. Do not fear them, be fierce instead and read up <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">over here</a>.</p><h3><strong>Make Your Mark</strong></h3><p>We’ve got a resplendent 3 x 3 gameboard, our CSS and JS are linked up, let’s make our mark, shall we?</p><p>Organize your <em>js/main.js</em> with these headings:</p><pre><em>/*----- constants -----*/</em></pre><pre><em>/*----- app&#39;s state (variables) -----*/</em></pre><pre><em>/*----- cached element references -----*/</em></pre><pre><em>/*----- event listeners -----*/</em></pre><pre><em>/*----- functions -----*/</em></pre><p>This bit of organization will help keep our code <strong>clean</strong> and <strong>readable</strong>. It will also help us organize our code so we can write more efficiently. Slay on, Cheryl, slay on.</p><p><em>What does it mean to make a mark? </em>Making a mark means that there is a place for the mark to be made:</p><pre><em>/*----- app&#39;s state (variables) -----*/</em></pre><pre>let board;</pre><p>Making a mark means that a game has been initiated.</p><p>Let’s use a function to initiate the board as an <a href="https://www.w3schools.com/js/js_arrays.asp">array</a> of 9 empty strings. Our JS doesn’t know anything about the HTML document yet. <strong>Each position in the JS array will correspond to a square on the HTML board.</strong> Let’s give ourselves a visual aid by mimicking the 3 x 3 grid from our HTML. The 3 x 3 structure of the array changes nothing. It could be written on one single line!</p><pre>function init() {</pre><pre>board = [</pre><pre>&#39;&#39;, &#39;&#39;, &#39;&#39;,</pre><pre>&#39;&#39;, &#39;&#39;, &#39;&#39;,</pre><pre>&#39;&#39;, &#39;&#39;, &#39;&#39;</pre><pre>];</pre><pre>};</pre><pre>//be sure to call the init function!</pre><pre>init();</pre><p>Making a mark means rendering a change in the game.</p><p>Let’s stub up a render function:</p><pre>function render() {</pre><pre>}</pre><p>Now, let’s think about what we want to do. This render function will need to <strong>iterate</strong> over our board array and “inject” the mark into the correct div. Let’s use a handy little function called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">.forEach()</a>. This function accepts a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">callback function</a> that it will call on each element in the array:</p><pre>function render() {</pre><pre>board.forEach(function(mark, index){<br>console.log(mark, index);<br>});</pre><pre>};</pre><p>Call render():</p><pre>function init() {</pre><pre>board = [</pre><pre>&#39;&#39;, &#39;&#39;, &#39;&#39;,</pre><pre>&#39;&#39;, &#39;&#39;, &#39;&#39;,</pre><pre>&#39;&#39;, &#39;&#39;, &#39;&#39;</pre><pre>];</pre><pre>// new code here<br>render();</pre><pre>};</pre><p>Go ahead and open a server then hit <em>cmd + opt + i</em> to check out your console! You should see all the index numbers from the board! Try throwing something into the empty strings on the board array and see what happens in the console.</p><p>Making a mark means that the mark shows up on the page.</p><p>Grab our squares:</p><pre><em>/*----- cached element references -----*/</em></pre><pre>const squares = Array.from(document.querySelectorAll(&#39;#board div&#39;));</pre><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from">Array.from()</a> function will make an array from all elements returned by <a href="https://www.w3schools.com/jsref/met_document_queryselectorall.asp">querySelectorAll</a>. Notice that querySelectorAll is finding the element with the id of <em>.board</em> and selecting <strong>all the div children</strong> of that element. This way, we didn’t have to give each square an id, select them individually, and build a new array. JavaScript did that for us! Pretty cool!</p><p>Pass those to render():</p><pre>function render() {</pre><pre>board.forEach(function(mark, index) {</pre><pre><em>//this sets the text content of the square of the same position to the mark on the board. </em></pre><pre>squares[index].textContent = mark;</pre><pre>});</pre><pre>};</pre><p>And now, you have made a mark, Cheryl! Treat yourself!</p><h3><strong>Take turns</strong></h3><p><em>What does it mean to take turns?</em> Taking a turn means that there is a turn.</p><p>Head back to the state section and throw down your turn variable like a boss:</p><pre><em>/*----- app&#39;s state (variables) -----*/</em></pre><pre>let board;</pre><pre>let turn = &#39;X&#39;;</pre><p>Taking a turn means that an event (such as ‘click’) has occurred.</p><p>Listen for the click on the board. We will need to “grab” an HTML element using <a href="https://www.w3schools.com/jsref/met_document_getelementbyid.asp">getElementById</a>() and then chain the event listener onto it:</p><pre><em>/*----- event listeners -----*/</em></pre><pre>document.getElementById(&#39;board&#39;).addEventListener(&#39;click&#39;, handleTurn);</pre><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a> takes two arguments, the event to listen for and a callback function to execute when the event is heard. We need to write that callback function:</p><pre><em>/*----- functions -----*/</em></pre><pre>function handleTurn(event) {</pre><pre>let idx = squares.findIndex(function(square) {</pre><pre><em>return</em> square === event.target;</pre><pre>});</pre><pre>};</pre><p>The ‘<a href="https://developer.mozilla.org/en-US/docs/Web/API/Event">event</a>’ is the click, the ‘<a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/target">target</a>’ is the element on which the event took place — the square we’ve clicked on. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex">findIndex()</a> finds the index of the square in our squares array that matches the square the user clicked!</p><p>Excellent work! You can change the world, Cheryl.</p><p>Did I say world? I meant <em>board</em>. Change the board we’re holding in state:</p><pre>function handleTurn(event) {</pre><pre>let idx = squares.findIndex(function(square) {</pre><pre><em>return</em> square === event.target;</pre><pre>});</pre><pre>// new code below</pre><pre>board[idx] = turn;</pre><pre>// check your console logs to make sure it&#39;s working!</pre><pre>console.log(board);</pre><pre>};</pre><p>Has your state changed? You’re on the right track in this game and in your life. You’ve got this. You can change the board for the better!</p><h3><strong>“X” and “O”</strong></h3><p>We still don’t have “O” included in this game which makes it easy to win, but not much fun to play. So, we’ll just update that bit of state using a ternary.</p><p>Ternaries seem to confuse people. Learn to write one today and thank yourself for all time. Here’s our logic: <em>If it is X’s turn, then assign the turn to O; if it is not X’s turn, assign the turn to X.</em> Let’s put that logic into the ternary structure:</p><pre>&lt;condition&gt; ? &lt;if condition is true, this&gt; : &lt;else if condition is false, this&gt;</pre><p>Place the assignment “turn =” in front of that ternary and try console logging it out. It’s ok if this takes a minute. Just breathe, Cheryl. Don’t forget to call that render() function once you’re all through. All together it should look like this:</p><pre>function handleTurn() {</pre><pre>let idx = squares.findIndex(function(square) {</pre><pre><em>return</em> square === event.target;</pre><pre>});</pre><pre>board[idx] = turn;</pre><pre>// This is tidy</pre><pre>turn = turn === &#39;X&#39; ? &#39;O&#39; : &#39;X&#39;;</pre><pre>// In an if statement it would look like: </pre><pre>// if (turn === &#39;X&#39;) {<br>// turn = &#39;O&#39; <br>// } else {<br>// turn = &#39;X&#39; <br>// };</pre><pre>// writing the ternary saved you from all that. </pre><pre>render();</pre><pre>};</pre><p>Ta-freaking-da! Now we have a Tic-Tac-Toe game! Nothing can dim the light that shines from within you!</p><p>Let’s fix our &lt;h2&gt; so our user gets the right message and knows when it’s their turn:</p><pre><em>/*----- cached element references -----*/</em></pre><pre>const squares = Array.from(document.querySelectorAll(&#39;#board div&#39;));</pre><pre>// new code below</pre><pre>const messages = document.querySelector(&#39;h2&#39;);</pre><p>When should we change the message? When we render!</p><pre>function render() {</pre><pre>board.forEach(function(val, idx) {</pre><pre>squares[idx].textContent = val;</pre><pre>});</pre><pre>// new code below</pre><pre>messages.textContent = `It&#39;s ${turn}&#39;s turn!`;</pre><pre>};</pre><p>The backticks (`) allow us to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literals</a> to embed JS expressions in strings.</p><h3><strong>Win Logic</strong></h3><p><em>What does it mean to win?</em></p><p>Winning means there’s such as thing as winning:</p><pre><em>/*----- app&#39;s state (variables) -----*/</em></pre><pre>let board;</pre><pre>let turn = &#39;X&#39;;</pre><pre>// new code below</pre><pre>let win;</pre><p>Every time a player takes a turn, we need to check if they made a winning move. Let’s start with our top row. It has the indexes 0 through 2. So, the winning <a href="https://www.w3schools.com/js/js_comparisons.asp">logic</a> will be: There is a win if there is a mark in index 0 and it matches the marks in indexes 1 and 2. Ternaries all day.</p><pre>win = board[0] &amp;&amp; board[0] === board[1] &amp;&amp; board[0] === board[2] ? board[0] : null;</pre><p>Note that we’re checking that there is something in board[0] first. If we just check that all three positions are the same, we’ll get a winner when they&#39;re all empty. The first board[0] prevents that. This ternary has three conditions, but it’s still the same structure:</p><pre>&lt;condition1 &amp;&amp; condition2 &amp;&amp; condition3 &gt; ? &lt;if all 3 conditions are true, this&gt; : &lt;else, this&gt;</pre><p>Use your console to check if your win variable is working correctly by typing <em>win</em> and seeing if your console returns true or false. You could write out all those statements and it would work for your win logic, OR…</p><h4><strong>Refactor</strong></h4><p>We have 3 (rows) + 3 (columns) + 2 (diagonals) = 8 possible ways to win. Let’s make an array of the indexes of winning combinations. This is where you may find the 3 x 3 shape of our board array helpful for finding the index numbers of winning combos. Make an array of combos where each element is a nested array of the index numbers of winning moves:</p><pre><em>/*----- constants -----*/</em></pre><pre>const winningCombos = [</pre><pre>[0, 1, 2],</pre><pre>[3, 4, 5],</pre><pre>[6, 7, 8],</pre><pre>[0, 3, 6], </pre><pre>[1, 4, 7],</pre><pre>[2, 5, 8],</pre><pre>[0, 4, 8],</pre><pre>[2, 4, 6]</pre><pre>];</pre><p>Create a new function that will test for the winner every turn:</p><pre><em>/*----- functions -----*/</em></pre><pre>function getWinner() {</pre><pre>// just stub it up for now.</pre><pre>}</pre><p>Now, let’s refactor our handleTurn() function to call getWinner() and assign its output to the win variable:</p><pre>function handleTurn() {</pre><pre>let idx = squares.findIndex(function(square) {</pre><pre><em>return</em> square === event.target;</pre><pre>});</pre><pre>board[idx] = turn;</pre><pre>// new code here</pre><pre>win = getWinner();</pre><pre>render();</pre><pre>};</pre><p>Cheryl, you are a treasure. Now, we need the getWinner() function to iterate through that winningCombos array and check if one of the players has a winning combination of marks on the board. We can use winningCombos.forEach() to do that. That way, we only need to write the win logic one time, but it will be checked against all 8 of our possible winning combinations. Our forEach() callback function will accept two arguments, the element in the array, and the index of the element: function(combo, index) Once again, we can use the same logic, but we’ll be testing if all three marks match a combo in the winning combos array. Give it a shot! You will end up with something like this:</p><pre>function getWinner() {</pre><pre>let winner = null;</pre><pre>winningCombos.forEach(function(combo, index) {</pre><pre><em>    if</em> (board[combo[0]] &amp;&amp; board[combo[0]] === board[combo[1]] &amp;&amp; board[combo[0]] === board[combo[2]]) winner = board[combo[0]];</pre><pre>  });</pre><pre><em>  return</em> winner;</pre><pre>};</pre><p>That looks like our logic from before, but we’ve written a function to check all the winning combos at once. Use the console.log() to check your function.</p><p>Werk! Let’s update our message so it shows the winner when there is a winner. This can be done in a single line using our friend, the ternary.</p><pre>messages.textContent = win ? `${win} wins the game!` : `It&#39;s ${turn}&#39;s turn!`;</pre><h3>Declare a Tie</h3><p>What does it mean to tie? It means the board is full and there are no remaining moves or opportunities to win. Let’s put that into the getWinner() function:</p><pre>function getWinner() {</pre><pre>let winner = null;</pre><pre>winningCombos.forEach((combo, index) =&gt; {</pre><pre><em>if</em> (board[combo[0]] &amp;&amp; board[combo[0]] === board[combo[1]] &amp;&amp; board[combo[0]] === board[combo[2]]) {</pre><pre>winner = board[combo[0]];</pre><pre>}</pre><pre>});</pre><pre>// new code below</pre><pre><em>return</em> winner ? winner : board.includes(&#39;&#39;) ? null : &#39;T&#39;;</pre><pre>};</pre><p>Or, if you want to see without the ternary:</p><pre>function getWinner() {</pre><pre>let winner = null;</pre><pre>winningCombos.forEach((combo, index) =&gt; {</pre><pre><em>if</em> (board[combo[0]] &amp;&amp; board[combo[0]] === board[combo[1]] &amp;&amp; board[combo[0]] === board[combo[2]]) {</pre><pre>winner = board[combo[0]];</pre><pre>}</pre><pre>});</pre><pre>// new code below</pre><pre>if (winner) {<br>  return winner <br>} else if (board.includes(&#39;&#39;)) {<br>  return null // if there&#39;s an empty space, return null (no winner yet)<br>} else {<br>  return &#39;T&#39; // no winner and no empty spaces? That&#39;s a tie!<br>}</pre><p>Now, let’s update the message so it won’t display ‘T wins the game!” if there is a tie. Try having a look at this nested ternary and translating it into plain-spoken language:</p><pre>messages.textContent = win === &#39;T&#39; ? `That&#39;s a tie, queen!` : win ? `${win} wins the game!` : `It&#39;s ${turn}&#39;s turn!`;</pre><p>The text content of the messages is going to be: if win is ‘T” then, “That’s a tie, queen!”, if there is a win then, “&lt;winner&gt; wins the game!”, else, “It’s &lt;turn&gt;’s turn.” It may be confusing at first glance, but that doesn’t make you any less of a badass. Go over it again or try writing out the equivalent in if…else statements. If you get stuck, don’t sweat it! I have written the solution below.</p><p>Classic if/else statement version:</p><pre>if ( win === &#39;T&#39; ) {<br>  messages.textContent = `That&#39;s a tie, queen!`<br>} else if (win) { <br>  messages.textContent = `${win} wins the game!`<br>} else {<br>  messages.textContent = `It&#39;s ${turn}&#39;s turn!`<br>}</pre><p>Ternaries are fun, but a word of caution: not everyone likes seeing them nested as it can diminish readability, but I don’t want you to be confused when you come across them.</p><h3>The Game is Finished</h3><p>The game is finished. Let’s get that reset button working so we can get a fresh start:</p><pre><em>/*----- event listeners -----*/</em></pre><pre>document.getElementById(&#39;board&#39;).addEventListener(&#39;click&#39;, handleMove);</pre><pre>//new code</pre><pre>document.getElementById(&#39;reset-button&#39;).addEventListener(&#39;click&#39;, init);</pre><p>I just re-used the init() function to reset the game, but you don’t have to. This is your world, Cheryl.</p><p>Go back over the working game and try challenging yourself to look for ways to improve it. Here are some ideas:</p><ul><li>Make it so players can keep score</li><li>Make it so players have the option of who can go first (right now, X always goes first)</li><li>Add some more badass styling</li><li>Make it so after a square is filled in with one mark it cannot be changed</li><li>See if you can re-write a function a different way</li><li>Make it responsive for users on mobile</li><li>Come up with your own improvement and build it out!</li></ul><h4>Slay on, Cheryl, slay on.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a889e4c20883" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-worlds-most-empowering-tic-tac-toe-javascript-tutorial-a889e4c20883">The World’s Most Empowering Tic-Tac-Toe JavaScript Tutorial</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>