<?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 Diana Liao on Medium]]></title>
        <description><![CDATA[Stories by Diana Liao on Medium]]></description>
        <link>https://medium.com/@dianaliao?source=rss-ec6d9bc39fcd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*22Wp9X1_8Zm70Z1NHW3wmw.jpeg</url>
            <title>Stories by Diana Liao on Medium</title>
            <link>https://medium.com/@dianaliao?source=rss-ec6d9bc39fcd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:27:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dianaliao/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[Git Your Feet Wet]]></title>
            <link>https://dianaliao.medium.com/git-your-feet-wet-8fc1be99d24?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc1be99d24</guid>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 18:42:06 GMT</pubDate>
            <atom:updated>2023-02-03T18:50:09.600Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Starting out with version control from the command line</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yh3OUWl4IiZdDOyw" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>(I originally started/planned this Git intro guide post over a year ago, after a month into my first developer job. But it turned into an abandoned project, as projects do. Now, I’m helping to mentor intro students over at <a href="https://codethedream.org/">Code the Dream</a>, and the topic is back in my life with increasing frequency. So it’ll be easier to refer to this article than typing it into Slack and Zoom repeatedly. 👋 Hi, students!)</p><p>Learning to code keeps getting easier, coming in the form of games and phone apps and some rather robust Web IDEs that make it so you only have to be able to use a browser to get started. But if you choose to write your own larger projects locally on a computer, especially in groups, learning to use a version control system like Git becomes essential. And if you’re like me, you also have to conquer some deep-rooted fear of the command line.</p><p>But it’s going to be okay. If for no other reason than the fact that part of why Git was created was to make it really really hard to make irrevocable mistakes.</p><p>Note: This is not meant to be a particularly comprehensive beginner’s guide to Git. These just happen to be <strong>the most useful commands I’ve used in my exact journey</strong>, including bootcamp<strong>. </strong>This also assumes you have already installed Git for your operating system and are going to be using GitHub to host your projects. (Guide <a href="https://docs.github.com/en/get-started/quickstart/set-up-git">here</a>.) Let’s go!</p><h4>What is Git?</h4><p>Git is a version control system (VCS) which is useful in tracking and managing changes in code. It does similar things you are familiar with when editing any document, like saving to files and undoing changes, but with a lot more tracking and documentation that makes it easy to see the history of the code and work asynchronously with a team. Git also allows you to easily revert your code to a previous (perhaps functional) state, without having to do things like save “MyCode-draft 1” and “MyCode-draft 2” and “MyCode-final” and “MyCode-final final” and so forth into different files, trying to remember which is which.</p><p>But it’ll take a little practice. You’ll learn to like it, I promise. (Especially the first time it gets you out of a jam. You’ll feel like a wizard.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*rYVGe7zymk_nANpnQm2Kpw.gif" /></figure><h4>A little more conceptual background</h4><p>Before getting into the commands, if you’re new, let’s try and grok some of the concepts and learn the vocabulary.</p><p>All of your code for a project will live in a code <strong>repository</strong>, or <strong>repo</strong> for short. A repository is like any other folder containing all of your code files (and that’s how it will look when you navigate through it), but it should have other things like documentation and a VCS like Git set up so the history of the code changes are also tracked. It’s a very powerful file folder.</p><p>One of a Git repo’s superpowers is the ability to save changes in the form of a <strong>commit</strong>. A commit captures a snapshot of your repo — the file structure and contents — along with other data like the code author, timestamp, and your <strong>commit message</strong>. They enable you to keep a history of your changes without saving draft after draft under different names, along with a note from the code author that describes the changes made. Note that each commit doesn’t contain all of your code, per se, but rather <strong>all of the changes since the previous commit</strong>. This is an important concept to keep in mind. The commits build on top of each other, and are structured so they can be reordered or even moved to a different branch entirely.</p><p>Another superpower is the ability to contain <strong>branches</strong>. Every repo has a default branch, which will likely be called main, or master in some older repositories. Think of this branch as the best representative and public face of your code. At any point in the development of your codebase, you may make other branches that come off of the main branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHH8qDSIOKO7SvK0KVf-ew.png" /><figcaption>Think of each circle as a commit. Image from <a href="https://openclipart.org/detail/278045">Openclipart</a></figcaption></figure><p>Branches are useful because you can experiment, break, test, and fix your code without touching the main branch. (Which is hopefully the most stable of your branches.) If you’d like to keep the changes you’ve made in a branch, you can <strong>merge</strong> them into the main branch, making mainbetter than ever!</p><p>To recap: a Git repo is a special folder for your code, where its changes are captured in the form of commits, like in a timeline. Git also allows you to seamlessly form branches of alternate timelines in the same folder, making it easy to compare the them and incorporate the differences.</p><h4>Excited? Here’s your survival guide!</h4><p>(Again, disclaimer: I will be focusing on specific use cases in this post that will most likely come up in a bootcamp setting while <strong>working alone</strong>. I won’t go into too much detail, and will cover some of the basics of working with others in a different post. And if you’re in my class, please still do the assigned Git readings first. 😄)</p><p>Starting out, you are most likely going to <strong>fork</strong> a repo on Github’s web interface to create your own copy. Go to your forked copy and then click on the green Code button and copy your HTTPS URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*jLGK_DEPvSXk6OUTV7msRA.png" /></figure><p>When you clone this repository to your machine, you will be creating a folder with its name. Navigate to where you’d like this folder to live. To <strong>clone</strong> enter:</p><pre>$ <strong>git clone &lt;URL&gt;</strong></pre><p>After it is done successfully, you should be able to find your repository by using the ls command.</p><pre>$ <strong>ls</strong><br>some-other-folder          your-repository-name           download.jpg            </pre><p>Navigate into your repository just like any other folder.</p><pre>$ <strong>cd your-repository-name</strong></pre><p>And now you’re in!</p><p><strong>Optional detour</strong>: Are you going to work on a different branch than the default?</p><pre># To create a new branch and immediately switch to it <br>$ <strong>git checkout -b your-new-branch-name</strong><br><br># To switch back to another branch<br>$ <strong>git checkout branch-name</strong><br># e.g. git checkout main</pre><p>(This is where we part ways for a bit and you open the repo in whatever code editor you have chosen and do your thing. I use VS Code and so I’d just use code . to open the directory. You can also open the editor first and open the folder. Anyway, code away, and save your amazing work.)</p><p>Now we are going to check on your changes, make sure all the files you want are <strong>tracked</strong>, <strong>stage</strong> the changes you want to keep, and them <strong>commit</strong>. All of these commands are run where we left off, in the main folder of your repository.</p><pre># To check to see what files you have changed or are untracked:<br>$ <strong>git status</strong><br><br># To check on the specific changes you&#39;ve made:<br>$ <strong>git diff</strong> </pre><p>I usually do both of these. I set my code editor to autosave often so it’s possible for my cat to do some edits that I have to find. Giving a look also helps to find any code breaks or console logging that were long forgotten.</p><p>At least some of the changes look good? Let’s <strong>stage</strong> those changes to a commit. (You get to pick and choose!)</p><pre># To add everything (in tracked files):<br>$ <strong>git add .</strong><br><br># To add only specific files (including any of them that are new and untracked):<br>$ <strong>git add &lt;filepath&gt;<br></strong># You can just copy and paste the paths given in &#39;git status&#39;<br><br># To add only specific changes (and not entire files), follow the prompts after:<br><strong>$ git add -p</strong></pre><p>You might want to double check git status one more time. Now to the <strong>commit</strong> the changes!</p><pre># To save them to a commit:<br>$ <strong>git commit -m &quot;</strong>&lt;your descriptive message here&gt;<strong>&quot;<br><br></strong># To skip the adding step above if you are absolutely sure you want to include all the changes you&#39;ve made:<br>$ <strong>git commit -am &quot;</strong>&lt;your descriptive message here&gt;<strong>&quot;</strong></pre><p>It is in your best interest to write a clear commit message. It will help you and anyone reviewing your code understand the changes. (You <em>can</em> commit without a message, or commit and change it later, or write a commit with a subject line + body format, but for now I suggest you practice one liners.) It is common convention to say what this commit <em>will achieve</em> when applied and not use past tense. For example, “Add biographical information to About page” or “Fix broken links in the menu”.</p><p>Let’s make sure this is all backed up to GitHub.</p><pre># To push up a brand new branch<br>$ <strong>git push -u origin &lt;your-branch-name&gt;</strong><br><br># To push back to GitHub if there is already a branch of that name:<br>$ <strong>git push</strong><br># You can always try `git push` on its own first and it will help you push a new branch</pre><p><strong>Merging your branches</strong></p><p>In a solo project, once you are sure you’d like all of the work in your branch incorporated to your main branch, you can merge easily via the command line.</p><pre>$ <strong>git checkout main</strong> # make sure you&#39;re in the receiving branch<br>$ <strong>git merge incoming-branch</strong></pre><p>If you are doing this as part of coursework, it’s common to submit a <strong>pull request</strong> before merging, which gives a space for comments or discussion. This is best done back on the GitHub website.</p><p>Navigate back to the page for your repo and click on “Pull Requests”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*LJGUB9yH0Oeq8LeLZO_gmw.png" /></figure><p>From the pull requests page, click on the green “Create Pull Request” button and follow the prompts. There will be an option to merge from the resulting pull request.</p><p>Merging is more complicated when you are checking for changes from a collaborator, but we’ll cover that later.</p><p><strong>A few more useful commands</strong></p><p>If you find that you’ve been working on the wrong branch but already saved some work (but not committed it), you can cut and paste like this:</p><pre>$ <strong>git stash</strong><br>$ <strong>git checkout desired-branch-name</strong><br>$ <strong>git stash apply</strong></pre><p>If you want to change the your most commit and haven’t pushed it yet:</p><pre># To amend the message or the files<br>$ <strong>git commit --amend<br><br></strong># To just undo the commit but keep the changes saved locally<br>$ <strong>git reset --soft HEAD~1<br></strong># This can undo mulitple, but let&#39;s keep it simple! Check &#39;git status&#39; here and make your changes and recommit.</pre><p>If you want to see your commit history:</p><pre>$ <strong>git log<br></strong># Hint: Type &quot;q&quot; when you are done browsing.<br><br># For a more compact version:<br>$ <strong>git log --oneline</strong></pre><p>That should help you muddle through a few solo projects! Let me know if there’s anything I should add, or what I should include in a followup post. To practice some git commands without working on your own project yet, here’s a <a href="https://learngitbranching.js.org/">great web-based tutorial</a>.</p><p>Happy coding, everyone!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc1be99d24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introvert’s Path to their First Tech Job (and Some Numbers)]]></title>
            <link>https://medium.com/geekculture/an-introverts-path-to-their-first-tech-job-and-some-numbers-d88e28c9f3b2?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d88e28c9f3b2</guid>
            <category><![CDATA[job-search]]></category>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Sat, 13 Nov 2021 06:52:58 GMT</pubDate>
            <atom:updated>2021-11-23T07:43:54.306Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Another bootcamp graduate anecdote for the enormous pile. Spoiler: it has to do with a lot of luck and timing.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xYfxQRUKN8_UgjFZ" /><figcaption>Photo by <a href="https://unsplash.com/@drew_beamer?utm_source=medium&amp;utm_medium=referral">Drew Beamer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After three months and ups and downs (mostly downs), I accepted a job offer after graduating coding bootcamp. Yay!</p><p>…</p><p>Okay, that was enough celebrating.</p><p>(Also I’ve dawdled on this post and I’m already a month into my job.)</p><p>Because of the cynical New Yorker child-of-immigrants I am, let me also loudly announce what I did <strong>*not*</strong> manage to do in this time period, which I was expecting to do:</p><ul><li>make a portfolio site I liked (bonus: stubbornly without template)</li><li>complete a post bootcamp project</li><li>finish a data structures course</li><li>consistently solve Leetcode medium problems</li><li>learn any number of other things on my to-study and to-do list (including more blog posts, per career services recommendation)</li></ul><p>This is all still bugging me a little bit, because of some guilt in getting a job even though I slacked in meeting my post-bootcamp goals. Layers upon layers of imposter syndrome. Not to mention that I actually wanted to do these things. (And am worried I’ll lose motivation to.) I think a lot of us get lost in the hustle and stress of trying to become a “no-brainer hire”. The job search is draining even when it’s going well and really lends itself to a daily feeling that you’ve constantly failed when all that’s happened is that you’ve <em>fallen short of an impossible goal of perfection</em>, which is constantly being redefined. (Today it might be going to a job fair and making 5 new connections, tomorrow it might be doing a hackathon, and next week you might lament not finishing that Udemy course. You need to learn to <a href="https://dianaliao.medium.com/preventing-post-bootcamp-burnout-99197dc7b337">forgive yourself</a>.)</p><h4><strong>First, as promised, some numbers</strong></h4><p>I kept track of my job/apprenticeship applications mostly on a Trello board. I’m missing some data here and there, but here’s the gist of how my job search went:</p><ul><li>32 applications, complete with cover letters and/or essays</li><li>12 first round interviews/assessments</li><li>6 final rounds…ish (I guess I don’t know for sure for sure, ya know?)</li><li>3–4 job offers (depending on your definition)</li></ul><p>Opportunities were found through:</p><ul><li>3 job fairs</li><li>3 community Slack workspaces</li><li>3 recruiters who found me via LinkedIn or <a href="https://www.pocitjobs.com/">POCIT</a></li><li>2 friends</li><li>a lot of support from Flatiron School career services</li><li>I don’t know it was actually kind of a blur that involved a bad cold by the end</li></ul><p>The only places I got to the final round with were through friends, career services, or a recruiter…in other words, that key to the job search I think we all hate at least a little: <strong>networking</strong>.</p><figure><img alt="A laptop with a video conference call on the screen with many participants on a desk with a mug of coffee." src="https://cdn-images-1.medium.com/max/1024/0*IsdkPSpqcPhISSgJ" /><figcaption>Networking in the pandemic era // Photo by <a href="https://unsplash.com/@cwmonty?utm_source=medium&amp;utm_medium=referral">Chris Montgomery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introvert’s mini guide to networking</h4><p>It’s not news that connections get you places. Even though I’ve known this, until this job search, I couldn’t bear deal with that stress. However, especially with bills looming, I knew I had to get out of my comfort zone. And similar to how I found remote immersive bootcamp to be the <a href="https://medium.com/geekculture/bootcamp-advice-for-my-former-self-a0fe74a5ef0d">best of all worlds</a> for my personality and/or “learning style”, the pandemic normalized more remote options than ever to get my network game on.</p><p><strong>Virtual Job Fairs</strong></p><p>I think I’ve only been to two in-person job fairs in my life. I associate them with dehydration, uncomfortable shoes, awkward handing of resumes, and fumbling the conversation. Nothing really saves you from that last one, but the first 3 need not apply!</p><p>The three virtual tech job fairs I went to this summer followed very different formats. They all had different drawbacks but here are some things they had in common:</p><ul><li>an asynchronous way to leave your resume and contact information</li><li>opportunity to speak to people 1-on-1 if you wanted to, sometimes just over text (yay no camera)</li><li>easy post-fair followup from employers, who already have all of your information from registration</li></ul><p>The fairs I went to were also all based around an affinity group — one focused on women, one for diversity, equity, and inclusion, and one for working against climate change. Values-based job fairs were key because:</p><ul><li>you know the employers care about what you do</li><li>they know you care about what they do</li><li>you learn what brilliant madness is out there in exciting fields (lookin’ at you, <a href="https://www.terra.do/climate-jobs-fair/professionals/">Terra.do</a>), renewing a sense of hope that maybe you can do good in this world</li></ul><p><strong>Virtual informational interviews</strong></p><p>Y’all. I’m loving this shift to video meetings. I’ve always been a fan because you don’t have to leave your house, the drinks are free, and you can leave with a click of a button. But now they’re the norm!</p><p>I don’t have particular tips for this one, except to not be as afraid of them. I’ve found them less intimidating over time because:</p><ul><li>Get anxious during conversations? Leave a lot of notes around off screen (sticky notes on the monitor!).</li><li>People pretty much only agree to meet if they are very happy to be speaking with you.</li><li>Except you know what else people like? Short meetings. Set it to 15–30 min if you like, so you know exactly how much sweat and smile you have to do. No waiting for the lunch bill or coffee to cool.</li></ul><figure><img alt="photo of a computer screen running a Slack workspace called “Time to Hack”" src="https://cdn-images-1.medium.com/max/1024/0*W8vPAfhJRYiXDhEb" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Online communities with job postings</strong></p><p>Though this includes a wide spread of sites and services, I am mostly talking about Slack and Discord. (Though I’ve heard people have luck in LinkedIn groups.) For those who don’t know, Slack workspaces and Discord servers are where groups of people can chat in organized channels or direct messages in an informal way. These are great because you can observe and read past messages to get settled and break the ice in any way you’d like (whether with a cat pic in the pets channel or a good old intro in a welcome channel). If you’re feeling too shy for that you can get started with reacting to messages with emoji. I obviously can’t vouch for every workspace or server, but good ones are out there! If you search for the name of your closest major city with “tech slack” there’s a fair chance that you’ll find one. I’m also in workspaces like <a href="https://rubyforgood.org/">Ruby for Good</a>, <a href="https://workonclimate.org/">Work on Climate</a>, and one for bootcamp alumni.</p><h4>Still job hunting? Hold on to hope!</h4><p>It’s hard. It’s kind of random. It’s definitely draining. I often laid down in between meetings or just straight up needed a nap after a 30 minute call. It’s hard now, but you’re starting what I hope to be a long and prosperous career. The extra hours you put in may pay out dividends.</p><p>There might (will) be some really hard times. You’re also allowed to take breaks. Real restorative breaks. Those breaks are what you need to make things happen. Bonus: Talking to friends and enjoying your hobbies are what make you who you are, and that is what will shine through in interviews to help you stand out.</p><p>Comments or quandaries? Let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d88e28c9f3b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/an-introverts-path-to-their-first-tech-job-and-some-numbers-d88e28c9f3b2">An Introvert’s Path to their First Tech Job (and Some Numbers)</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with the Canvas Element]]></title>
            <link>https://dianaliao.medium.com/getting-started-with-the-canvas-element-5e5fb26f4de7?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e5fb26f4de7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 05:52:26 GMT</pubDate>
            <atom:updated>2021-08-18T05:58:30.361Z</atom:updated>
            <content:encoded><![CDATA[<p><em>And making basic graphics with JavaScript within this magical rectangle</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HjQfAVaDApPhK3IH" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For my Phase 4 project at bootcamp, I wanted to make a drawing app, but had no idea where to start. Since it was going to be built with a React/JS frontend, I focused on looking at packages since it seemed like flashy and complicated functionality. Little did I know what I’d actually end up taking advantage of was a humble HTML element, <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas">canvas</a>.</p><p>This element is not unlike a painting canvas — it creates a drawable section in an HTML document where you can use JavaScript to create graphics and animations through the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">Canvas API</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API">WebGL API</a>.</p><p>To create a canvas element, all you need to do is supply height and width attributes. Just starts with making a rectangle! It’d also be ideal to include an id for ease of finding the element on the DOM or styling it later. Once this element is made, you can use JS to add things like shapes, colors, lines, and text.</p><p>Let’s take a look by trying to draw the Japanese flag 🇯🇵, a white flag with a red circle in the center. We’ll make the canvas element the entirety of the flag itself, and add a border with CSS.</p><pre>&lt;!-- HTML file: --&gt;<br>&lt;canvas id=&quot;test-canvas-1&quot; width=&quot;300&quot; height=&quot;200&quot;&gt;<br>&lt;/canvas&gt;</pre><pre>---</pre><pre>/* CSS file: */<br>canvas#test-canvas-1 {<br>  border: 1px solid black;<br>}</pre><p>At this point we just have a rectangle with a black border.</p><p>We could do other things to make the red circle (like CSS) or the flag (including just inserting an image of the flag…) but for demo purposes, let’s see this canvas get used!</p><p>The first thing we have to do in JavaScript is nab that canvas element from the DOM. (I wrote a <a href="https://javascript.plainenglish.io/your-first-week-in-dom-manipulation-ac4d0b2589a">little primer in DOM manipulation</a> a little while ago if you need a refresher!) After that, we’ll grab the drawing context for the canvas.</p><pre>var canvasEl = document.getElementById(&quot;test-canvas-1&quot;)<br>var canvasContext = canvasEl.getContext(&quot;2d&quot;)</pre><p>Now that we have access to the drawing context, we have access to a whole slew of methods!</p><pre>// create a white rectangle the size of the canvas<br>canvasContext.fillStyle = &quot;white&quot;<br>canvasContext.fillRect(0,0,canvasEl.width,canvasEl.height)</pre><pre>// draw a circle and fill it in red<br>canvasContext.beginPath()<br>canvasContext.arc(150, 100, 60, 0, 2 * Math.PI)<br>canvasContext.fillStyle = &quot;red&quot;<br>canvasContext.fill()</pre><p>Here’s a look at the result.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fjacjyd%2Fembed%2Fpreview%2FNWjZqqW%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DNWjZqqW&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fjacjyd%2Fpen%2FNWjZqqW&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e92af607140454a33ef80f0be57931a/href">https://medium.com/media/3e92af607140454a33ef80f0be57931a/href</a></iframe><p>That was fun and easy enough to follow, but might not seem the best way to make simple shapes. It’s also rendered as an image without any semantic HTML options available. But the beauty is when it’s integrated into user interaction and there are more functions in the JavaScript!</p><p>The MDN tutorial for canvas includes a section in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations">basic animations</a>, where you can learn how to create a solar system demo or a clock. And soon I’ll be writing more about how to use React and the humble canvas element to create a drawing app! Until then, this hopefully demystifies the basics, and has you playing around with more of <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">the methods available</a> to the context object! You can use the CodePen environment above as a starting point.</p><figure><img alt="an animation of a squiggle being drawn on a web page titled “Sketchy”" src="https://cdn-images-1.medium.com/max/640/1*OWc3Jbpy6AbQmfQrsFePdQ.gif" /><figcaption>I lacked inspiration for this sample drawing…</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e5fb26f4de7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing Post Bootcamp Burnout]]></title>
            <link>https://dianaliao.medium.com/preventing-post-bootcamp-burnout-99197dc7b337?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/99197dc7b337</guid>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[job-search]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 23:08:04 GMT</pubDate>
            <atom:updated>2021-08-14T01:32:32.997Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A pep talk for self-care and forgiveness while doing the job of finding a job</em></p><figure><img alt="An antique red sign saying “For Hire”" src="https://cdn-images-1.medium.com/max/1024/0*x2_nfQSBVzS8mTpY" /><figcaption>Photo by <a href="https://unsplash.com/@clemono?utm_source=medium&amp;utm_medium=referral">Clem Onojeghuo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After finishing your degree or bootcamp, or just really just anytime that you decide you are going to make a change, comes the job search. At best, it’s a busy and exciting time, but most likely, it’s stressful and a little soul-crushing. (Because how else will you write a convincing cover letter or ace the interview if you don’t actually on some level believe you and the company are kismet?)</p><p>After a bit of a break, or well, “part-time” job searching, I’ve just jumped into the real deal last week. Job fairs and proactive meeting scheduling, coding most days, and finding a groove. The ramp up period had been hard enough, and as much as we all need the do’s and don’ts of cover letters and elevator pitches, I think we also need to give ourselves a little grace. Disclaimer: I haven’t found a job yet. 😅 So take all of this with a grain of salt.</p><p><strong>You can’t do everything everyone else is doing</strong></p><p>Leaving a bootcamp, your classmates are your first lifelines and network in the tech world. Hopefully you’ve bonded with some and will be able to rely on each other through the rough times, and celebrate in the good times! But shortly after classes are over, talking to this social support becomes a constant reminder of all of the things you need to do:</p><p><em>“I really need to dig into learning data structures and algorithms”</em></p><p><em>“I am working on my resume all day”</em></p><p><em>“I just got my portfolio site up!”</em></p><p><em>“I signed up for some mock interviews”</em></p><p><em>“I just really need a break and I’m going to take a vacation”</em></p><p><em>“I’m going to learn Python/Node/Vue/[insert language, framework, or tool here] next”</em></p><p>If you’re not careful, you will have the mental to-do list of over a dozen people combined, which one person just can’t do! It’s great to compare notes and keep each other motivated, but remember that there is simply no way to work on what *everyone* else is working on. Anything you get done is a win.</p><p><strong>What’s right for them may not be what’s right for you</strong></p><p>Similar to the above point of not getting bogged down by the additive effect of hearing too many people’s plans, everyone’s journey is going to be a little different. We’ve all got individual strengths and weaknesses and varying amounts of privilege and resources. Our lives outside of “work” (in this case the job search) are bound to have speed bumps and stop signs at different points.</p><p>Some people are in a place to be able to spend the time and energy to hit the ground running and keep running, but that might not be you through no fault of your own. Maybe you have some family or personal issues to deal with, or maybe you haven’t yet grown your network just yet. Maybe you’re dealing with chronic illness and there just aren’t as many spoons available. Maybe you’re still earning money so you don’t fall completely into debt, or taking some other classes, but this leaves you less time to do everything else. Also we’re still amidst that pesky global pandemic, and baseline stress levels are high.</p><p>It’s okay.</p><figure><img alt="animated gif of fuzzy anthropomorphized balls of orange and purple giving a hug" src="https://cdn-images-1.medium.com/max/500/1*96iippEzCaJ_LFxZZ0XcHw.gif" /></figure><p>You’ll get there in your own time. And if someone finds a job before you, that doesn’t mean you’re any less than they are, or have any less potential.</p><p><strong>Job hunting is a job, and productivity tools apply</strong></p><p>All that self-forgiveness aside, make sure you’re setting yourself up for success. Getting through bootcamp took a lot of self-discipline and self-motivation. Don’t let those muscles atrophy!</p><p>Block out hours in your calendar or planner for tasks (coding, finding leads, networking, studying). Use something like <a href="https://trello.com/en-US">Trello</a> or a spreadsheet to track your job opportunities. Set up standups in the morning or algorithm practice with accountability partners (lookin’ at you, cohort ham fam) as often as is productive for you.</p><p>If nothing else, setting aside job search work hours will help you be able to leave the rest for leisure and recharge. Which you also need!</p><p>Take breaks. Your brain won’t function without them.</p><p><strong>Luck is at play, and you can’t control it</strong></p><p>There is definitely value to working towards opportunities and building the no-brainer case for your hiring and fit at your dream job. But there is always some amount of chance, including networking to get you towards said opportunities, around getting your face in front of the right people at the right time. When are these right times? It might be a job fair, or it might be your cousin’s housewarming party. Your dream company might have a job opening this week, or maybe it’ll be in two months and you’ll have no way of knowing! Luck can be kind and luck can be cruel.</p><p>Just because you don’t get the gig doesn’t mean you did anything wrong.</p><p><strong>This is a giant learning experience, and you’re better for having tried at all</strong></p><p>After graduating, friends were eager to set me up with job leads and ask around. I told them at first that I wasn’t ready yet. I “had to” learn more about X, Y, and Z, and clean up my projects, and learn a few new languages, and do a few mock interviews first…</p><p>Luckily a job posting that was too easy to try for came up, and I snapped out of that quickly. And literally had an interview the next day. Trial by fire!</p><p>I was trying to be perfect before even trying. The fallacy being that there’s no way to achieve perfection. My “official” first mock tech interview will be next week, but in the meantime, I’ve had tech interviews solving brain teasers and discussing RESTful APIs, done a code challenge in Python and Django, talked through a function in Go, and taken a timed assessment in web development which included two coding problems (and some jQuery, which I had to dig deep to remember). I didn’t ace all of these (the Go specifically was a complete surprise…) but despite a lifetime of trained negativity, I didn’t see them as failures. I am more experienced for the next interview, and making mistakes is making me better for the next time around. (And none of the languages or frameworks I mentioned above were ones that I claimed to have any profiency in.)</p><figure><img alt="black cat curled up and sleeping on a teal blanket" src="https://cdn-images-1.medium.com/max/1024/1*AxHLES9xEvtX0gCUm0j9Yw.jpeg" /><figcaption>channel the chill of your favorite critter</figcaption></figure><p><strong>In conclusion, you’re doing great!</strong></p><p>Because I have to believe I am as well.</p><p>Thanks for reading! I hope to return with my normal coding fare and questionable analogies soon. But I’m actually still taking some breaks while I can this summer, and I hope you do too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99197dc7b337" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bootcamp Advice for My Former Self]]></title>
            <link>https://medium.com/geekculture/bootcamp-advice-for-my-former-self-a0fe74a5ef0d?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0fe74a5ef0d</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[wellness]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 20:50:47 GMT</pubDate>
            <atom:updated>2021-07-01T17:19:04.942Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Reflecting on 15 weeks of camaraderie and code</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RtcNKp1144Mee-7G" /><figcaption>Photo by <a href="https://unsplash.com/@garrhetsampson?utm_source=medium&amp;utm_medium=referral">Garrhet Sampson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>About a month ago, I completed Flatiron School’s immersive software engineering bootcamp. Since COVID restrictions were still in place, all of it took place remotely over Zoom. I did my best to prepare myself for what I was getting into, the shock of returning to a school environment after over a dozen years, and also living a while without income. But there were bound to be things I didn’t know to prepare for, and if you’re anything like me, I hope this post will serve you well!</p><p>How do you know you’re anything like me? Here’s some of my background to see it resonates:</p><ul><li>mid-30s career-changer (most recently an overworked nonprofit professional)</li><li>engineering background in undergrad (chemical)</li><li>grew up with a toxic pressure to excel in school</li><li>managed to start and finish prework early over a longish period (scholarship determination was partly based on prework completion at time of review and so I powered through the beginning quickly, and also delayed my start date to give my organization ample time to find a replacement)</li></ul><p>Basically, I’m a person who’s been in a stressful working environment for some time, with time management skills (or some coping mechanisms for the lack thereof 😅), who may have been relatively overprepared during the pre-work phase (and I am so so so grateful for that). I take that back: <strong>there is no way to be overprepared for bootcamp.</strong></p><p>You’ve probably heard tips like “do the prework” or “minimize distractions” or “get on a good sleep schedule”. But those felt pretty obvious to me. Here are a few more things I wish I had fully considered and internalized.</p><figure><img alt="runners on a wide street with varied outfits" src="https://cdn-images-1.medium.com/max/1024/0*ZbD0Y0Unknsal1_3" /><figcaption>Photo by <a href="https://unsplash.com/@mzemlickis?utm_source=medium&amp;utm_medium=referral">Mārtiņš Zemlickis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>15 weeks is neither a marathon nor a sprint; pace accordingly</strong></h4><p>Part of my choice to leave my job and finally attend bootcamp once the opportunity became real (accepted &amp; funded), was that I have done much worse and less with 4 months of my life — stayed too long in a job going nowhere, dated people I possibly didn’t even like in the first place, and generally not achieving my goals. 15 weeks was nothing!</p><p>So I called it my Diana-issance, made a plan to set myself up for success and reinvent myself.</p><p>My first month at bootcamp was a relative breeze. The work was copious and hard, but I was riding high from leaving my job and feeling “on vacation”. I finished all of the labs. I slept on a schedule. I didn’t buy any takeout or delivery and meal prepped on the weekends. I worked out almost every day during lunch. I unplugged and meditated or journaled each night. I was a new person!</p><p>But then came the mid-bootcamp-life-crisis. My old terrible sleep schedule returned (hello 3am) and I spent my lunch breaks watching Netflix and eating donuts. Some natural ebb and flow in my mental health, as well as unforeseen events, led to some rough spots. I was burnt out for a while. And once I stopped being perfect, I fell apart and felt like I came to a stop. I think I aimed for too much general self-improvement, and doing that <em>and</em> actually doing the bootcamp work proved unviable.</p><p><em>Advice</em>: Budget and order that delivery. Let go of fitness goals for a little while. Forgive yourself if you fall behind. <strong>Find a sustainable groove.</strong> Bootcamp is perhaps not the right time to become your best self, and that’s okay!</p><h4><strong>Grades mean nothing, and are besides the point</strong></h4><p>Though there were technically code challenges and final projects to pass, grades didn’t exactly matter beyond that. Unlike traditional school experiences (especially those where not all of the students really wanted to be there), what matters isn’t the transcript, but actually <em>learning the material. </em>Are completing the labs and/or getting the deliverables to work probably a good way to make sure you know the material? Yeah. Is it still satisfying to rock a code challenge and get a perfect score? Sure. But in reality, you learn <em>more</em> from making mistakes and getting feedback from instructors.</p><p>My first actual coding feedback came over a full month after beginning the program (a comment about considering an edge case in a function I wrote), and it was a breath of fresh air. It turns out that human factor was what I had been missing. I was focused on my preconceptions about school — getting perfect grades and doing my homework. But with coding, there are so many ways of solving a problem, and scoring well on a test really doesn’t help you learn much. Learning from your coding shortcomings is where you really grow.</p><p><em>Advice</em>: Don’t confuse the means with the ends. Throw out the concept of grades. Demand some attention from instructors if you want it so you can really maximize the 15 weeks. If anything, failing at least occasionally is the goal, so you can learn from the process.</p><figure><img alt="animated gif of two peoeple talking with the caption “we will fail together”" src="https://cdn-images-1.medium.com/max/480/1*zKvITdlvcTjidwl1rvq3Sg.gif" /></figure><h4><strong>Working with a project partner is difficult. Full stop.</strong></h4><p>Pair programming and working with others can be valuable, fulfulling, motivating, and even a ton of fun! But despite all of the benefits, it will inevitably take more work in a bunch of ways than working on your own. That’s okay!</p><p>I knew I was out of practice doing group work coming into this bootcamp and the stress surrounding it was pretty high in mind. I have a lot of social anxiety as a baseline and navigating interpersonal dynamics AND a large project was not something I was looking forward to. Whenever I ran into a conflict, no matter how minor, I kept seeing it as a failure in myself if I didn’t get along with my project partner perfectly, especially if they were known to be an easy-going and nice person. (Spoiler, I actually think I would say that *everyone* in my cohort fits that description.)</p><p>But there is no shame in admitting that going from working independently for two weeks straight only to have to be tethered to someone else with a different eating/sleeping/coding/everything routine is going to take a little work. Overcoming the unavoidable conflicts is just a skill that needs to be practiced.</p><p><em>Advice</em>: Accept that you can’t be best friends with your project partner AND pair seamlessly every minute of every day. Take breaks and set boundaries. Perhaps even above the final product, focus on what you can learn from one another and make sure you both have a fulfilling experience, whatever that means for you.</p><h4><strong>Live remote learning just might be the best environment ever (for me)</strong></h4><p>If I were faced with the split second decision between in-person immersive learning, and self-paced online learning, I would choose the latter. Not a difficult choice. Commuting and having to be around people are not my favorite things!</p><p>But with more thought, I know the immersive program would keep me more structured and motivated, offer an immediate network upon graduation, and I’d finish faster.</p><p>Also the scholarships I found were only applicable to the in-person programs.</p><p>So, thanks COVID, for this wonderful in-between opportunity!</p><p>All of the community and cameraderie, but none of the running-late rush hour Lyfts to class and fear of breaktime chitchat. I already knew I liked working remotely from my previous jobs — easy bathroom and snack access, occasional cat in my lap, no need for headphones, and the list goes on. But beyond those perks, I didn’t realize until too late that I could really bend the school experience to my will.</p><p>I could lean into my more fidgety tendencies, and meal prep or do stretches during lecture so I could focus better. I could sing aloud which helps me work out problems sometimes. Short naps for the greater good were also possible. I only figured this out halfway through bootcamp, but it made all the difference.</p><p><em>Advice</em>: If this is your first time in whatever learning environment you’re going to be in, especially if it’s after a long break, leave your expectations behind! Don’t think of it as gaming the system (at least in a bad way) but rather best tailoring your experience.</p><figure><img alt="Black cat looking at a laptop screen on a lap" src="https://cdn-images-1.medium.com/max/1024/1*lgclMv6QbhDHNWma_mq_-w.jpeg" /><figcaption>Sqkrz was great at helping me keep up with Slack messages</figcaption></figure><h4><strong>Seriously, learn to forgive yourself</strong></h4><p>This one isn’t new to me (and I think I even mentioned it earlier) but it’s something a lot of us can use constant reminders of in all areas of life. I was mostly prepared to forgive myself for taking breaks from coding, or not finishing my homework, but here is a sampling of what I actually had to “forgive” myself for (quotes because forgiveness might not have been necessary):</p><ul><li>not checking Slack in time to help someone with a bug</li><li>not having the energy (after a full day) to do more independent study</li><li>not exercising for a few days</li><li>not eating more plant-based foods</li><li>not making people laugh every time I talk to them</li><li>talking too much about my feelings</li><li>not talking enough about my feelings</li><li>having any feelings that affected me in any way whatsoever</li></ul><p><em>Advice</em>: Have your friends check in (seriously, give them a schedule) and have them reassure you that you’re doing great. And also that you’re human. Because you’ll listen when other people say this.</p><p>I can go on for a few more pages about how I felt about bootcamp (I didn’t even get into the cohort love!) and what I learned outside of coding week-by-week, but I’ve indulged enough for now. Feel free to let me know if you have any questions or want to talk further!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0fe74a5ef0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/bootcamp-advice-for-my-former-self-a0fe74a5ef0d">Bootcamp Advice for My Former Self</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unraveling the Mystery of the Multi-tasking Single Thread]]></title>
            <link>https://dianaliao.medium.com/unraveling-the-mystery-of-the-multi-tasking-single-thread-21e0cd98103b?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/21e0cd98103b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Fri, 28 May 2021 16:20:12 GMT</pubDate>
            <atom:updated>2021-06-15T00:55:53.338Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How JavaScript Imitates Concurrency and Makes Promises</em></p><figure><img alt="several traffic lights hanging on a wire giving mixed signals" src="https://cdn-images-1.medium.com/max/1024/1*Cw7VzWcgBwW33JAZOKwiBg.jpeg" /><figcaption>Where do all of these functions go anyway?</figcaption></figure><p>Around mid-bootcamp, we were introduced to <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch">fetch()</a>, our first asynchronous method. I knew it involved something called a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>, a chain of<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a> , which dealt with the return of promises, and it was all for the sake of allowing other JavaScript code to run in case the network request took a while. Without this feature, the stack could become “blocked” waiting for a longer process to complete and the user would be unable to interact with the website in the meantime. At the time, learning that general pattern to grab JSON data from an API was enough. As I am nearing the end of my final weeks of bootcamp, attempting a project built upon user interaction with asynchronous code everywhere, I found myself needing to understand how the JavaScript call stack gets filled more and more. So how does a single-threaded language like JS manage to simulate concurrent processing?</p><h4>One stack, with a dedicated staff</h4><p>JavaScript indeed runs off of a single call stack of truth, and that makes it single-threaded. But there are a lot more helpers behind the scenes! An asynchronous function will send code elsewhere to a place where it will be handled separately outside of the call stack, and eventually be placed in a separate queue. An <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">event loop</a> will wait for the call stack to empty and then take a “message” with an associated function (i.e. the callback function) from the queue and place it on the call stack to then be run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b6jEsTafpMef-mEr" /><figcaption>Photo by <a href="https://unsplash.com/@picoftasty?utm_source=medium&amp;utm_medium=referral">Mae Mu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let me describe a totally plausible scenario (for a dream anyway). Imagine there is a large platter of pancakes at breakfast with your mom. You love pancakes so this is great. She places one on your plate and your job is to eat it. Great! But your mom knows you better and starts placing another pancake on your plate immediately as you finish them, and it might even be piling up. Amid all of this you eye a waffle iron across the way and say “hmm, I’d like a waffle as well”. *poof* Some comforting childhood figure appears, perhaps Patrick Stewart, and he says “I’ll make it so” and gets started on that waffle. After that confusing event, your mother continues to guilt you into eating the rest of the pancakes. Eating all of these takes some time, even in dream land, and the waffle is ready. However, having waffle in between pancakes is just not allowed, so P-Stew hands it off to LeVar Burton who just keeps holding onto that waffle until you’re done with your mega stack-o-pancakes, at which point he is free to place that waffle onto your plate.</p><p>In this scenario, eating all of the food (mostly pancakes) is a big function execution context that needs to be completed, your plate is the call stack, making the waffle is the asynchronous function, your eating the waffle is the callback function, Patrick Stewart is an API, and LeVar Burton is the event loop.</p><p>Now that I’ve made it more confusing, let’s take a look at its parts!</p><p>The <em>call stack</em> is how a JS interpreter (such as your browser) keeps track of the multiple functions it has to run and in which order during the compilation phase. The JS call stack is last-in-first-out (LIFO), meaning you have to work from the top down.</p><p>(Side note: But aren’t functions invoked in the order in the code in more of a first-in-first-out pattern? This stack is not to be confused with compiling lines of code in order. The stack contains the function <em>execution context </em>created when a function is invoked<em>.</em> If you think of a function<em> </em>with many other nested inner functions, you can imagine that the inner functions need to resolve before you can continue on with the outer functions until you reach the global context. So don’t worry, the stack isn’t backwards!)</p><p>Here is a much better illustration of how the concurrency model works from this <a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">blog post</a> written by Alexander Zlatkov:</p><figure><img alt="animation of an example call stack, web API, callback queue, and event loop" src="https://cdn-images-1.medium.com/max/808/1*__wPgGBodnci5NWcaa_Aqw.gif" /><figcaption>Animation from “<a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">How JavaScript works: Event loop and the rise of Async programming + 5 ways to better coding with async/await</a>” by <a href="https://medium.com/@zlatkov">Alexander Zlatkov</a></figcaption></figure><p>When it’s an asynchronous function’s turn in the call stack, it is still dealt with right then and there (and leaves the call stack in a timely manner), but it is actually handled by another API that will return a callback accordingly to wait in a queue. As far as the call stack is concerned, it’s done and over with and is ready for the next function.</p><h4>Mind your P’s (promises) and Queues</h4><p>This single queue is not quite the whole story anymore since the introduction of standardized promises and the async/await function construction.</p><p>Your average old school asynchronous function like setTimeout or setInterval will get processed in the browser or Node API (it’s not actually a JS function!) which will send a callback function to the queue explained in the general gist/mega breakfast analogy explained above, where it waits for the call stack to empty before it is processed. This occurs even if you specify the delay to be zero milliseconds. Once it’s async, everything else takes precedence:</p><pre>setTimeout(() =&gt; console.log(&quot;bye!&quot;), 0) <br>console.log(&quot;hi&quot;)<br>console.log(&quot;how are you?&quot;)<br>console.log(&quot;well, I gotta get going.&quot;)</pre><pre>/* <br>console output:</pre><pre>hi<br>how are you?<br>well, I gotta get going.<br>bye! <br>*/</pre><p>If you run the above code in your browser console, you’ll see that even though the delay is set to be zero, the callback function in the setTimeout will run after all other synchronous code.</p><p>Beginning in ES6, JS also utilizes a separate <strong><em>job queue</em></strong> used by promises. Once functions that return a promise (such as fetch) resolve, they are fast-tracked to the next available slot in the synchronous code. So there are actually two separate lines waiting to go on the call stack rollercoaster, the regular queue and the fast-pass job queue. These priority queue members may also be indicated by the then() method, such as in the familiar pattern of fetch(&#39;someUrl&#39;).then(response =&gt; response.json()).then(data =&gt; handleData(data)) . The then() returns a Promise , taking up to two arguments: a callback function upon the success of a promise and one for the failure. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">Promise</a> object represents the eventual results (whether successful or not) of an asynchronous operation. It has three states: pending, fulfilled, or rejected. The creation of promises is either built into the function (like fetch() or then()) or you can explicitly create promises with a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise">Promise constructor</a>.</p><p>Using <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await">async/await syntax</a> will also create promises. It’s syntactic sugar for Promise creation. In general, placing async before your function declaration makes it asynchronous and return a Promise. That’s it! Within the async function, you can also use await which acts as a then() in that it creates another pausing point to wait for the code on the right to resolve before moving on to the next.</p><pre>async function interruption(){<br>   const message = await &quot;INTERRUPTING&quot;.concat(&quot; STARFISH&quot;)<br>   console.log(message)<br>}</pre><pre>setTimeout(() =&gt; console.log(&quot;bye!&quot;), 0)<br>interruption()<br>console.log(&quot;hi&quot;)<br>console.log(&quot;how are you?&quot;)<br>console.log(&quot;well, I gotta get going.&quot;)</pre><pre>/* <br>console output:</pre><pre>hi<br>how are you?<br>well, I gotta get going.<br>INTERRUPTING STARFISH<br>bye!<br>*/</pre><p>In the above snippet example, you can see that even though the first asynchronous function setTimeout is called before the second interruption function, since interruption uses utilizes promises, it was placed in the job queue and beats out the “bye!” from setTimeout.</p><p>Thanks for reading this quick post on async functions and how JS manages to seem multithreaded! Let me know if any terminology is off or you have other comments.</p><p>I try to include a cat in every post, so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcZGkmfb87tpae5trua8qg.jpeg" /><figcaption>Promise for tuna, status: unfulfilled</figcaption></figure><p>If you still have questions (you should), these are some great resources to check out:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8aGhZQkoFbQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8aGhZQkoFbQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8aGhZQkoFbQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/204a98bf5f658b677a94bd62e0d85854/href">https://medium.com/media/204a98bf5f658b677a94bd62e0d85854/href</a></iframe><ul><li><a href="https://medium.com/dailyjs/asynchronous-adventures-in-javascript-promises-1e0da27a3b4">Asynchronous Adventures in JavaScript: Promises</a></li><li><a href="https://codeburst.io/javascript-engines-how-do-they-even-work-from-call-stack-to-promise-dcfce39f0c38">JavaScript Engines: How Do They Even Work? From Call Stack to Promise</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21e0cd98103b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weaving an Accessible Web]]></title>
            <link>https://dianaliao.medium.com/weaving-an-accessible-web-f008e35bcb7d?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f008e35bcb7d</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[coding-bootcamp-students]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Thu, 13 May 2021 03:34:01 GMT</pubDate>
            <atom:updated>2021-06-16T19:57:17.991Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Considerations for even the newest coders in HTML</em></p><figure><img alt="Dog sitting in front of computer monitors, turned to look at the camera" src="https://cdn-images-1.medium.com/max/1024/0*htI1eRU6hF1A7AwH" /><figcaption>Photo by <a href="https://unsplash.com/@pavelherceg?utm_source=medium&amp;utm_medium=referral">Pavel Herceg</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The web is for everybody. (And maybe some smart pets?) The UN has even decreed that the internet is a <a href="https://www.article19.org/data/files/Internet_Statement_Adopted.pdf">human right</a>. If you are reading this article, you most likely use the internet on a daily, if not hourly or continuous basis. There is very little that cannot be enhanced or improved in some way through the help of the internet. Perhaps it’s comparison shopping, or looking up the weather before an outdoor trip, or finding a job or apartment. Having use of the internet gives us an advantage we didn’t have without it.</p><blockquote>“The Web is fundamentally designed to work for all people, whatever their hardware, software, language, location, or ability. When the Web meets this goal, it is accessible to people with a diverse range of hearing, movement, sight, and cognitive ability.”</blockquote><blockquote>— <a href="https://www.w3.org/standards/webdesign/accessibility">W3C, Accessibility</a></blockquote><p>So how do we make sure that everyone can use the internet? <strong>Web accessibility</strong> plays a large role. Over <a href="https://www.cdc.gov/ncbddd/disabilityandhealth/infographic-disability-impacts-all.html">a quarter of people</a> in the United States have some type of disability, and that number rises as people age. Even more people will be affected by temporary disability in their lifetime, such as a result of an accident or surgery recovery. Even if you think a site is “fine” and works for “most people” now, you’ll probably wish more apps were made for aging eyes or more friendly to those with repetitive stress injury or arthritis sooner than you think! Accessibility is not limited to addressing disabilities, and includes making sites for those with limited resources (e.g. not the newest iPhone on high speed WiFi).</p><p>Here are a few examples of considerations for website accessibility:</p><ul><li>Does this page convey information on a screen reader for those who need or prefer audio?</li><li>Are these colors contrasted enough for bright sunlight, color blindness, or other contrast sensivity conditions?</li><li>Can this site be navigated with a keyboard without a mouse? Vice versa?</li><li>Can an older machine on slower internet load this site in a useful amount of time?</li><li>Is the text easy to understand? How about for a non-native speaker? Have you considered a translation option?</li></ul><p>Though we should strive to approach 100% accessibility, it is both easy and impossible to fully achieve. There are entire legal teams involved in <a href="https://medium.com/@krisrivenburgh/the-ada-checklist-website-compliance-guidelines-for-2019-in-plain-english-123c1d58fad9">keeping resources compliant</a>, and even the easy-to-use a11y project checklist has <a href="https://www.a11yproject.com/checklist/">over 50 items</a> to consider based on W3C’s <a href="https://www.w3.org/WAI/standards-guidelines/wcag/">Web Content Accessibility Guidelines (WCAG)</a>. But not to let “perfect be the enemy of good”, there are things even someone just starting in their journey as a web developer (as I am!) can be aware of.</p><h4>Semantic HTML Tags for Containers</h4><p>In theory, you could get away with constructing sites with&lt;div&gt; and &lt;span&gt; elements all day (as we did pre-HTML5), maybe adding some classes to assist with styling and help you remember what they are for, like class=&quot;header&quot; for an element containing a logo or class=&quot;nav&quot; for an element containing helpful links to main sections of the site. But ultimately, those tags are not very descriptive. Is this div an article? Or a menu bar? When you sketch out the layout of your room, you may draw a rectangle to represent a couch, but without a good label, it could also be a table, or a bathtub. Instead, you could use <a href="https://www.w3schools.com/html/html5_semantic_elements.asp">semantic element tags</a>, like &lt;header&gt;, &lt;nav&gt;, and &lt;main&gt;, making it easier for both the developer and user to get a sense of what information is where on the page. They convey meaning to the content within them, as described in the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Semantics">docs</a>. They were introduced in 2014 with HTML5, so if you learned HTML before that and haven’t picked it up since, it’s definitely worth a skim!</p><h4>Inline Semantic HTML Elements</h4><p>The semantics don’t stop at naming containers and sections of the page. You can give context and indicate if something is a &lt;time&gt; or &lt;address&gt;, highlighted text with &lt;mark&gt;, or a &lt;code&gt; block. These tags can make it easier for someone to quickly find contact or event information, or know that some unusual combination of words and sounds is actually code.</p><p>There are two pairs of tags that often get interchanged, &lt;i&gt; &amp;&lt;em&gt; (which will usually lead to <em>italicized</em> text) and &lt;b&gt; &amp; &lt;strong&gt; (which will lead to <strong>bolded</strong> text). However, they have different meanings. &lt;i&gt; and &lt;b&gt; are used just for styling while &lt;em&gt; and &lt;strong&gt;, as their names may suggest, are meant to assign <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em">emphasis</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong">importance</a> to the text, and will be read accordingly by screen readers. If the effect you are looking for is merely cosmetic, try to use styling and not the semantic tags.</p><p>Here’s <a href="https://www.w3schools.com/html/html5_semantic_elements.asp">a reference</a> for the tags again. Read them through and think about using them on your next mock-up!</p><h4>Form Labels for Clickability</h4><p>Forms are everywhere. Every time I learn a new part of web development, there’s always some forms topic waiting, much to my chagrin. But there’s a reason for that. Forms are a big part of a user’s experience, like signing up for an account, entering payment details, or searching for information. If you’ve ever made one you probably know about the &lt;label&gt; tag. If bound properly to the input field, a user can click anywhere on the label, and that field will come into focus to be typed in. This is helpful for those who may have trouble using their mouse steadily, or anyone who’s ever fumbled on their smartphone, blaming their “fat fingers”.</p><p>Here’s a quick demo: try to check all the boxes!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fjacjyd%2Fembed%2Fpreview%2FbGqVwya%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DbGqVwya&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fjacjyd%2Fpen%2FbGqVwya&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/666310573ef87bccd8a35dca5d920b02/href">https://medium.com/media/666310573ef87bccd8a35dca5d920b02/href</a></iframe><h4>Tabindex for Navigating</h4><p>Elements can be given a tabindex attribute to determine which elements and in what order they receive focus when you press the Tab key. Forms, buttons, and links are automatically put into this list, but you can also manually assign and order them as makes sense in the design of your site. Try pressing tab on the next site you’re on…you might find yourself taking advantage of it on well-designed sites in the future!</p><h4>Alt Text for Images</h4><p>All images should be provided with alt text which will be displayed if the image doesn’t load (like in areas with unreliable internet), or for screen readers to pick up. As these are made to serve as stand-ins for the photos, be sure to be descriptive. For example in this photo:</p><p><strong>Okay alt text</strong>: “Cat”</p><p><strong>Better</strong>: “Black cat with blue collar”</p><p><strong>Maybe even better</strong>: “Black cat with yellow eyes sitting in a lap wearing a blue inflatable recovery collar looking up at the camera”</p><figure><img alt="A black cat wearing a blue inflatable collar looking up at the camera" src="https://cdn-images-1.medium.com/max/1024/1*jdWRTtyDLUnU1IqcVcdVAg.jpeg" /><figcaption>alt text is not to be confused with a caption, which is more for providing detail and flavor accompanying the image. For example, this cat is not very happy with the situation.</figcaption></figure><h4>Using Text instead of Screenshots</h4><p>If you are including examples of text, like code snippets for a coding blog, try to use a text-based medium over a screenshot whenever possible. This means that a screen reader can handle the code or someone curious can copy and paste it. Medium uses <a href="https://embed.ly/">Embedly</a>, which allows for easy integration with other apps. So in addition to using a code block (activated using 3 backticks in a new line — ```), you can easily embed code from a Github <a href="https://gist.github.com/">gist</a> or sites like <a href="http://codepen.io/">codepen.io</a> (used above), <a href="https://jsfiddle.net/">JSfiddle</a>, and <a href="https://scrimba.com/">Scrimba</a>. As a bonus, these embeds also more interactive!</p><h4>Utilize the Internet You Know and Love</h4><p>Ready to move on from the basics? Search around! Here some tools you can use as well to test out sites and accessibility:</p><ul><li><a href="https://www.funkify.org/">Funkify</a>, a browser extension that allows to you simulate various disabilities and conditions, including those based on vision, cognition, motor function, and dyslexia</li><li><a href="https://caniuse.com/">Can I Use…</a>, which have tables which show what front end features are supported by which browsers. For example, here’s the <a href="https://caniuse.com/css-sticky">compatibility</a> for the CSS attribute position: sticky . (Spoiler, Internet Explorer doesn’t support it. Or a lot of things. Seriously, stop using Internet Explorer. Tell other people to stop too if they have a choice.)</li><li><a href="https://developers.google.com/web/tools/lighthouse/">Lighthouse</a>, an open source automated tool to check and rate your website on a variety of criteria, which you can use right in Chrome DevTools!</li></ul><p>Fun note on the term “a11y” used earlier — it’s a numeronym that <a href="https://www.a11yproject.com/about/#what-does-the-term-a11y-mean">stands for accessibility</a>! There are 11 letters in between “a” and “y” and it conveniently spells a relevant word.</p><p>I know these tips don’t cover much, and I personally already struggle to remember to stay on top of these, but we code, we live, and we learn. Let me know of any of the many corrections I should make!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f008e35bcb7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Cheatsheet to Understanding DOM Manipulation]]></title>
            <link>https://javascript.plainenglish.io/your-first-week-in-dom-manipulation-ac4d0b2589a?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac4d0b2589a</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 18:14:52 GMT</pubDate>
            <atom:updated>2021-04-27T11:46:23.967Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A short JavaScript primer for the overwhelmed front-end newbie.</em></p><figure><img alt="illustrated drawing of a person with their head in their hands in front of a laptop" src="https://cdn-images-1.medium.com/max/1024/1*fvH52srrY0o6xq-WvohSEw.png" /><figcaption>Image by <a href="https://pixabay.com/users/haticeerol-14967706/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=5752322">Hatice </a>from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=5752322">Pixabay</a></figcaption></figure><p>The structure of my Bootcamp had us learning a back-end in Ruby on Rails first, and then we popped right into JavaScript. With Ruby, we had months of legwork in the basics, and with JavaScript, it was oh, about a weekend, followed by a firehose of a week.</p><p>We jumped into applying JavaScript to <a href="https://www.w3schools.com/js/js_htmldom.asp">DOM</a> manipulation pretty quickly too, while my brain was still adjusting to the finer points of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a> vs <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for…in</a> vs <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for…of</a> vs <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach</a> (Real quick, in the same order: creates a loop, creates a loop through object properties, creates a loop through array elements, loops through elements of an array with a neat and tidy callback function).</p><p>Practice makes perfect (or at least, perfunctory), and here is the cheatsheet for JavaScript DOM manipulation that I wish I had at the beginning. This may be very specific to our version of the Bootcamp curriculum, but hopefully, it can help you, too!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*R0pxYyFLI2qpU5K9Hr80gw.gif" /></figure><h4><strong>Reacquaint yourself with CSS Selectors</strong></h4><p>Before even getting to JavaScript itself, know that most manipulation done with plain JavaScript will involve <a href="https://www.w3schools.com/cssref/css_selectors.asp">selectors</a> to point to specific elements (a type of node) in the DOM. If you haven’t worked with CSS much before, it’s a lot to take in, so keep your reference of choice handy. This will get you through the bigger parts:</p><ul><li>element: you can use html tags themselves as selectors<br>e.g. div, p, img , ul</li><li>.className: select by class by preceding the name by a “.” <br>e.g. using .profile-pic to select &lt;img class=“profile-pic” alt=&quot;demo profile photo&quot; src=&quot;photo.jpg&quot;/&gt;</li><li>#idName: select by id by preceding id by a “#” <br>e.g. #log-out-button to select &lt;button id=“log-out-button”&gt;&lt;/button&gt;</li><li>element[attribute=“value”]: select by specific attribute other than class or id<br>e.g. li[data-id=“3”] to select &lt;li data-id=“3”&gt;&lt;/li&gt;</li><li>outerElement innerElement: use a space between selectors to select all innerElement within/descended from outerElement (no matter how nested)</li><li>outerElement &gt; childElement: use a “&gt;” to indicate a childElement whose <em>direct</em> parent is the outerElement (cannot be further nested)</li></ul><h4>Start to identify parts of the DOM tree</h4><p>Some of the first methods you’ll be using to get your feet wet will be used on the Document. As defined the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document">MDN Web Docs</a>:</p><blockquote>The <strong>Document</strong> interface represents any web page loaded in the browser and serves as an entry point into the web page&#39;s content, which is the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core">DOM tree</a>.</blockquote><p>Our interface into the magics of the web! To start grabbing or making those tree branches, we can use the following.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector">document.querySelector</a>(“selector”): this will return the first element on the DOM that satisfies the specified selector. If you would like to return all of them, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll">document.querySelectorAll()</a>.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement">document.createElement</a>(“tagName”): this will return a brand new empty element, with the HTML tag of tagName , e.g. div, p, img, ul</li></ul><p>It would probably be best to start assigning these to variable names, in order for them to be more easily used later.</p><pre>const profilePic = document.querySelector(&quot;img.profile-pic&quot;)<br>// assigns the first &lt;img&gt; element with class of &quot;profile-pic&quot;</pre><pre>const newProfileDiv = document.createElement(&quot;div&quot;)<br>// assigns to a brand new &lt;div&gt; for future use</pre><h4>Branch out and prune 🪴</h4><p>In the above two methods, we were able to find elements and also create elements. But right now they’re just stored in variables and waiting, and we haven’t done anything to them yet.</p><p>Here are some basic ways to do that:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild">parentElement.append</a>(childElement) : this will place the childElement after the last child within the parent (There is a very similar function called <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild">appendChild()</a> that work for all nodes, with small differences).</li></ul><pre>newProfileDiv.append(profilePic) </pre><pre>console.log(newProfileDiv)</pre><pre>/*<br>   &lt;div&gt;<br>      &lt;h3&gt;Some stuff already in the div&lt;/h3&gt;<br><strong>      </strong><strong>&lt;img class=“profile-pic” alt=&quot;demo profile photo&quot; src=&quot;photo.jpg&quot;/&gt;</strong><br>   &lt;div&gt;<br>*/</pre><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/prepend">parentElement.prepend</a>(childElement) : this will place the childElement before other child elements in the parent.</li></ul><pre>newProfileDiv.append(profilePic) </pre><pre>console.log(newProfileDiv)</pre><pre>/*<br>   &lt;div&gt;<br><strong>      </strong><strong>&lt;img class=“profile-pic” alt=&quot;demo profile photo&quot; src=&quot;photo.jpg&quot;/&gt;</strong><br>      &lt;h3&gt;Some stuff already in the div&lt;/h3&gt;<br>   &lt;div&gt;<br>*/</pre><ul><li>You can also call methods on child elements, such as<a href="https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/before">before()</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/after">after()</a> to achieve similar results</li></ul><pre>const existingChildElement = newProfileDiv.querySelector(&quot;h3&quot;)</pre><pre>existingChildElement.before(profilePic)<br>console.log(newProfileDiv)</pre><pre>/*<br>   &lt;div&gt;<br><strong>      </strong><strong>&lt;img class=“profile-pic” alt=&quot;demo profile photo&quot; src=&quot;photo.jpg&quot;/&gt;<br></strong>      &lt;h3&gt;Some stuff already in the div&lt;/h3&gt;<br>   &lt;div&gt;<br>*/</pre><pre>---<br>OR<br>---</pre><pre>existingChildElement.after(profilePic)<br>console.log(newProfileDiv)</pre><pre>/*<br>   &lt;div&gt;<br>      &lt;h3&gt;Some stuff already in the div&lt;/h3&gt;<br><strong>      </strong><strong>&lt;img class=“profile-pic” alt=&quot;demo profile photo&quot; src=&quot;photo.jpg&quot;/&gt;</strong><br>   &lt;div&gt;<br>*/</pre><ul><li>profilePic.remove(): you can giveth and taketh away — this will remove the profile picture &lt;img&gt; from the DOM</li></ul><h4>Get to the main event (which is actually a lot of other events)</h4><p>The interactivity that JS offers largely comes from <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventListener">event listeners</a>. When triggered by things like clicks, mouseovers, or key presses, the listener will perform a callback function. These are the main arguments in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a> function. If we wanted to insert the profile picture upon clicking on the existing &lt;h3&gt; text, it might look something like this:</p><pre>existingChildElement.addEventListener(&quot;click&quot;, (event) =&gt; event.target.after(profilePic))</pre><p>The Event object is created once the specified event type occurs, in this case, click. It has a mess of properties (look into it with console.dir(event)), the most immediately useful one being target, the element notified by the event. In this case, event.target is simply existingChildElement, but once you start using <a href="https://dmitripavlutin.com/javascript-event-delegation/">event delegation</a> or forms, the target may be less readily apparent.</p><h4>Meet your friend, dataset</h4><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset">dataset</a> of an element is a versatile property that gives access to <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*">data-*</a> custom data attributes that allow information to be exchanged between the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML">HTML</a> and its <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model">DOM</a> representation by scripts. Okay, that was a mouthful. Let me start over.</p><p>Earlier, when giving an example of a custom attribute to choose by selector, I used li[data-id=“3”] to select &lt;li data-id=“3”&gt;&lt;/li&gt; . Attributes that begin with “data-” are actually stored in “<em>dataset</em>” property. You can conveniently store an id number, or any property, following a syntax convention demonstrated below:</p><pre>const exampleLi = document.querySelector(&#39;li[data-id=“3”]&#39;) </pre><pre>exampleLi.dataset.id // &quot;3&quot;<br>exampleLi.dataset.id = 51 <br>console.log(exampleLi) = &lt;li data-id=“51”&gt;&lt;/li&gt;</pre><pre>exampleLi.dataset.fosterCat = &quot;Cocoa&quot; <br>console.log(exampleLi) = &lt;li data-id=“51” data-foster-cat = &quot;Cocoa&quot;&gt;&lt;/li&gt;</pre><figure><img alt="photo of a seal point cat belly and paws" src="https://cdn-images-1.medium.com/max/1024/1*ueK3Zs0ODBQLtjrc5baLHg.jpeg" /><figcaption>Rub that belly. Cocoa was my first foster from <a href="https://www.kingstreetcats.org/">King Street Cats</a>.</figcaption></figure><p>Attributes in the “dataset” as accessed in JS show up as “data-” in the HTML. Furthermore, the names of the attributes follow their respective naming conventions and are automatically converted: camelCase for JS and kebab-case/dash-style in the HTML.</p><pre>element.dataset.camelCaseName = &quot;not a camelCase name&quot;<br>// [data-camel-case-name = &quot;not a camelCase name&quot;]</pre><p>You don’t really have to know about .dataset from the get-go, but getting exposed to how the attribute names will change should help a bit.</p><h4>And get to know the docs</h4><p>You’ll probably want to get to know .classList, .innerHTML, .textContent and so many more. The internet is both friend and foe right now. But mostly your friend. The answers are out there (and probably on MDN for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">JS</a> &amp; the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction">DOM</a>). Oh, and learn to use your browser’s dev tools! (Here’s <a href="https://www.keycdn.com/blog/chrome-devtools">a guide</a> for Chrome.)</p><p>Alright, past me (and current you), get back to learning JavaScript. And let me know if I should change anything.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac4d0b2589a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/your-first-week-in-dom-manipulation-ac4d0b2589a">A Beginner’s Cheatsheet to Understanding DOM Manipulation</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[Mighty Polymorphic Tables]]></title>
            <link>https://dianaliao.medium.com/mighty-polymorphic-tables-c27f411e7c4b?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27f411e7c4b</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[active-storage]]></category>
            <category><![CDATA[polymorphic-association]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[activerecord]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Sat, 17 Apr 2021 06:25:46 GMT</pubDate>
            <atom:updated>2021-04-21T19:54:45.934Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Untangling the polymorphic association, and a teeny tiny bit about Active Storage</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8_lXV0DosXSOW6gt" /><figcaption>Photo by <a href="https://unsplash.com/@federize?utm_source=medium&amp;utm_medium=referral">Federico Beccari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the beautiful things about the Rails framework is the built-in relationships given to us by <a href="https://guides.rubyonrails.org/active_record_basics.html">Active Record</a>. Active Record is a gem that provides Rails’ Object-Relational-Mapping (ORM) functionality. This allows our different models to talk to each other via their relationships by setting them up with the appropriate foreign keys and adding associations like belongs_to and has_many in their class definitions. For example, let’s say we have a message board app with a User model and Post model, where a post is written by one user, but an individual user may have many posts.</p><pre>class User<br>   has_many :posts<br>end</pre><pre>class Post<br>   belongs_to :user<br>end</pre><p>The table housing the Post objects will contain a foreign key for an instance of User that it “belongs” to. (The foreign key can get into the table in any number of ways, whether manually or generated by Rails.) With these macros in place, we can easily find an array of a user’s posts by calling user_instance.posts! Very convenient.</p><p>The relationships make some intuitive sense (in English), and are explained in the Ruby on Rails Guide for <a href="https://guides.rubyonrails.org/association_basics.html">Active Record Associations</a>. They are: belongs_to, has_one, has_many, has_many :through, has_one :through, and has_and_belongs_to_many . (That last one looks like a mouthful, but if you understand join tables and has_many :through, you’re golden!) The guide also provides for guidance on choosing between the similar ones. But if you keep going down the page you will see…</p><h4>Polymorphic Associations</h4><figure><img alt="animated gif of the Mighty Morphin Power Rangers" src="https://cdn-images-1.medium.com/max/250/1*TEI4g-0z4O7cl04sdt9yEg.gif" /><figcaption>Copyright law on gifs is iffy, but I had to do it.</figcaption></figure><p>It all made sense until now. Things had other things, or belonged to something. Well, that is still the case in polymorphic relationships, but with a twist. Let’s read on:</p><blockquote>“With polymorphic associations, a model can belong to more than one other model, on a single association.”</blockquote><p>Okay, helpful. But let’s see this in action!</p><p>The example from Rails Guides shows one way you might set up a Picture class definition, whose instances may belong to either an Employee or Product.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12e17613a070f0d26a5241f5f0fc1d40/href">https://medium.com/media/12e17613a070f0d26a5241f5f0fc1d40/href</a></iframe><p>The belongs_to and has_many macros are familiar, but notice that Picture doesn’t seem to directly belong to either Employee or Product, and they are linked via imageable. (The naming convention for the alias of a polymorphic table ends in -able. However, you can set this name to what works best for you and put them into the migration tables and class definitions!) If there were only one model that was associated with a picture, say, an employee, the pictures table would contain a foreign key employee_id, which would correspond to the primary key of the Employee instance it belongs to. However, since both employees and products can have pictures, this is replaced by an imageable_type and imageable_id, corresponding to the model name (either employee or product) and primary key, respectively. Pretty clever!</p><p>One alternative to using the polymorphic approach in this situation would be to use a single table inheritance (STI) model to create two separate tables for pictures, perhaps EmployeePicture and ProductPicture. But using a polymorphic table allows for one multi-purposePicture table.</p><p>There are <a href="https://www.freecodecamp.org/news/single-table-inheritance-vs-polymorphic-associations-in-rails-af3a07a204f2/">pros and cons</a> to using a polymorphic association over a STI model, with one important drawback being a loss in data integrity without a strict foreign key column and less isolated model relationships. However, it does have a <strong>big advantage in flexibility</strong> if you expect to expand.</p><p>As an example, imagine we have a dog shelter. A person can adopt many dogs. Right now, people just sign some paperwork, pay a fee, and adopt the puppo. This can be achieved in two models, with the adoption information stored on the Dog table.</p><figure><img alt="ERD showing a Person model with a has many relationship to a Dog model" src="https://cdn-images-1.medium.com/max/518/1*RYDcUT94T3GkUB1WBw_ETQ.png" /></figure><p>But maybe we decide to up our services a bit. The adoption comes with a follow-up consultation, a free vet visit, specific paperwork depending on the dog, and more detailed information that start to add a lot of columns to the Dog table. It begins to make sense on the backend for the adoptions to have their own methods and attributes. So we add an Adoption model and set up our relationships so that people are associated with adoptions, which are in turn tied to a specific dog.</p><figure><img alt="ERD showing a Person class joined to a Dog class by an Adoption class" src="https://cdn-images-1.medium.com/max/806/1*CTUgMBR6OOlvuKsT8bCe5Q.png" /></figure><p>As our reputation and great adoption practices become more well known, we decide to branch out to adopting out cats.</p><figure><img alt="photo of a black cat on a cat bed, with a blue bow on top" src="https://cdn-images-1.medium.com/max/1024/1*2vxpVN0WDgPgm9cp1WRsIQ.jpeg" /><figcaption>This little treasure and more are actually adoptable from <a href="https://www.kingstreetcats.org/">King Street Cats</a> in the DC area</figcaption></figure><p>To accomodate our new friends, we could create a more general Animal table, with columns like “name”, “color”, and “age” that apply to both dogs and cats, but also with additional columns that only apply to one or the other, such as a cat’s FIV status or how often a dog should be walked (which is all the time because they are a good dog yes they are). This works, but there are many cells left empty if they are not applicable (and who wants null or N/A cells everywhere), and we run back into the problem of an over-bloated table, like when the Dog model held the adoption data. Plus, you might want to branch out to more animals and this would only get worse.</p><p>This is when you may choose to use a polymorphic relationship for the Adoption model!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b65770e566c125e50a9720597e3f690/href">https://medium.com/media/3b65770e566c125e50a9720597e3f690/href</a></iframe><p>Now you can accomodate as many other types of animals that may come your way, storing key attributes and methods for them, and have a single type of adoption record that can fit all of them.</p><figure><img alt="ERD showing a Person model linked by an Adoption model to several other animal models in a polymorphic association" src="https://cdn-images-1.medium.com/max/854/1*m07HHK2oMxxDLbORxHUR3A.png" /><figcaption>I don’t know what you have to know about a lizard, but I assume it’s different from a hamster.</figcaption></figure><p>Whether or not you choose to use a polymorphic association is a matter of design choice, but if you believe your domain may grow in a way that might cause multiple models to have a similar relationship to the same model, it’s a good option to consider!</p><h4>Just a little bit about Active Storage</h4><p><a href="https://edgeguides.rubyonrails.org/active_storage_overview.html">Active Storage</a> is another great built-in part of Rails, which allows a easy file upload for a user to the cloud (or your local disk for development), while also attaching the file to an instance of a model, such as a picture for a profile or sales listing. The feature is extremely easy to use and set-up, and I recommend giving it a shot.</p><p>When you install and add Active Storage to your app, it creates two tables: active_storage_blobs and active_storage_attachments . The second table is, you guessed it, a <em>polymorphic table</em>!</p><figure><img alt="A text message exchange where author wrote “hey. hey. active storage uses a polymorphic table. there’s a polymorphic table in my computer RIGHT NOW”" src="https://cdn-images-1.medium.com/max/792/1*kAVOVlDr_qpiHz6fFzSvjQ.png" /><figcaption>My honest-to-Buddha initial reaction sent to a developer friend upon finding this out. Just realizing now it says right there this happened on a Saturday morning. #bootcamplyfe</figcaption></figure><p>It is a join table with columns for a “record_type”, “record_id”, and a “blob_id”. (A <a href="https://dev.mysql.com/doc/refman/8.0/en/blob.html">BLOB</a> is a most excellent data type that even has subtypes like TINYBLOB, MEDIUMBLOB, and LONGBLOB. I know, right? Almost makes databases seem cute.)</p><p>Anyway, “polymorphic” might sound less intuitive than the rest of the Active Record associations naming scheme, but they’re a small modification that can make a big difference. And then you can <a href="https://kotaku.com/super-metroids-creators-want-you-to-save-the-animals-1818880901">save all the animals</a>.</p><p>Is anything about this not quite right? Have any questions? Let me know! Just like all of you, I’m a programmer on a journey. (And very early on that journey at that.)</p><p>Additional resources:</p><ul><li><a href="https://www.freecodecamp.org/news/single-table-inheritance-vs-polymorphic-associations-in-rails-af3a07a204f2/">Single-table inheritance vs. polymorphic associations in Rails: find what works for you</a></li><li><a href="https://semaphoreci.com/blog/2017/08/16/polymorphic-associations-in-rails.html">Rails Techniques: Using Polymorphic Associations - Semaphore</a></li><li><a href="https://culttt.com/2016/01/13/creating-polymorphic-relationships-in-ruby-on-rails/">Creating Polymorphic relationships in Ruby on Rails</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27f411e7c4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wham Bam, Thanks, Params]]></title>
            <link>https://dianaliao.medium.com/wham-bam-thanks-params-bc8bbb6c150b?source=rss-ec6d9bc39fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc8bbb6c150b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[strongparams]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Diana Liao]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 14:11:49 GMT</pubDate>
            <atom:updated>2021-03-31T18:55:42.343Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How “params” is generated, used, and is stronger than a plain hash</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riZsouf2AINzb5Et-AUrQg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/qimono-1962238/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1495858">Arek Socha</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1495858">Pixabay</a></figcaption></figure><p>So you’ve gotten started with Ruby and you’re ready to bring your code to life with Rails! You’ve gotten the basics of a <a href="https://learn.co/lessons/rails-model-view-controller-readme">Model-View-Controller</a> (MVC) design down, your <a href="http://bin/rails%20generate%20model%20Comment%20commenter:string%20body:text%20article:references">RESTful routes</a> are set, and the server’s up and running. The index view was a breeze, but now you’re trying to render a view of a single instance of your model and you recall the standard syntax for that route (for a cat, because, why not):</p><pre>get ‘cats/:id’, to: ‘cats#show’, as: ‘cat’</pre><p>Huh, where’s that :id coming from and where does it go? This route syntax is indicating to your application that the :id will dynamically be determined by the value in the URL, which corresponds to the primary key of the instance of Cat from the database you want to see. For example:</p><pre>http://&lt;server-domain&gt;/cats/42</pre><p>would bring up information on a cat with an :id of 42.</p><p>But how does that :id get passed from the URL to the controller to retrieve the right cat? Nested in the HTTP request is an object, which contains the cat’s id number in a key-value pair. This allows us to find the cat with code like:</p><pre>class CatsController &lt; ApplicationController</pre><pre>  def show<br>    @cat = Cat.find(params[:id])<br>  end</pre><pre>end</pre><figure><img alt="photo of a cat, captioned “where did params come from?”" src="https://cdn-images-1.medium.com/max/1024/1*xf-4uA3cd6NW6b1eSpalJg.jpeg" /><figcaption>Plot twist, it’s a database of photos of the same cat. My foster cat.</figcaption></figure><h4>Where did the params hash come from?</h4><p>The params is a hash-like object which allows users, whether they know it or not, to send information along with requests to the server. (These parameter objects are not quite hashes, but more on that later.) Some of the more common ways params will be sent to your controller are through the URL itself, a query parameter, or a form. Let’s go over those briefly.</p><p><strong>The URL</strong></p><p>As described in the example above, the params may contain information from the URL in plain sight, like when it identified the primary key of the Cat object the user wanted to find.</p><p><strong>Query parameters</strong></p><p>As you travel around the web, take note of any question marks that appear in the URLs (or Uniform <em>Resource</em> Locators) of the pages you are browsing. The “?” delimits the boundary between the resource and the <em>querying string</em>, a key-value pair that is communicated through the params.</p><p>For example, when you use a search engine, you are sending search terms to run some sort of query. You can see some evidence of this in the results page. If you go to DuckDuckGo and enter “cat photos”, the page you get back will have something like /?q=cat+photos in the URL.</p><p>Query parameters are not limited to searching. You may also often see <a href="https://en.wikipedia.org/wiki/UTM_parameters">UTM parameters</a> (e.g. ?utm_source=) in your address bar, which can track if a user has reached a site through an e-mail campaign or a different website, or any number of things! Parameters are everywhere, and contain a lot of useful information.</p><p>As a quick use example, as the administrator of animal databases, let’s say you branched out from cats and now work with dogs. You entered these dogs into the database as they came (…or used the <a href="https://github.com/faker-ruby/faker">Faker gem</a> to generate some) and when grabbing a list of them through Dog.all, they display in primary key order.</p><p>But what if a user wanted to sort them alphabetically? You could make a new page called index_a_to_z_.html.erb and use a differently ordered list, possibly involving new routes or at the very least, a new view.</p><p>Or you could create a link to reload the index page, <em>with parameters, </em>and use some logic in your controller index action to display a different order.</p><p>The link in your index view and index action in your dogs controller could look something like this:</p><pre>&lt;-- dogs/index.html.erb --&gt;</pre><pre>&lt;%= link_to &quot;See the Dogs in Alphabetical Order&quot;, dogs_path(:sort =&gt;&#39;alpha&#39;) %&gt;</pre><pre>---</pre><pre># dogs_controller.rb</pre><pre>def index<br>  if params[:sort] == &#39;alpha&#39;<br>    @dogs = Dog.order(:name) <br>    # set instance variable to a list ordered by &#39;name&#39;<br>  else<br>    @dogs = Dog.all<br>  end<br>end</pre><p>Result: <a href="http://localhost:3000/dogs?sort=alpha">http://localhost:3000/dogs?sort=alpha</a></p><figure><img alt="animated demonstration of reloaded index page with dogs in alphabetical order" src="https://cdn-images-1.medium.com/max/360/1*ovC4zhTRUn7UrP54I1WJdA.gif" /></figure><p><strong>Form submissions</strong></p><p>Another direct way you may encounter params early on is when you implement a form on your web interface. When a user enters information in a “Contact Us” form, their name and any other information they entered are sent to the controller (and probably ultimately written to your database) via params. As params behave like hashes, information can be infinitely nested and hold quite a lot!</p><p>A user wants to add another dog to the database. Let’s take a look at an simple example form and the resulting params object. To add a dog, the user must enter the dog’s name and choose the dog’s type, as predetermined by theType table.</p><pre>&lt;!-- dogs/new.html.erb --&gt;</pre><pre>&lt;h1&gt;Add a Doggo!&lt;/h1&gt;</pre><pre>&lt;%= form_with model: @dog do |f| %&gt;<br>  &lt;%= f.label &quot;Name of doggo&quot; %&gt;<br>  &lt;%= f.text_field :name %&gt;&lt;br&gt;<br>  &lt;%= f.label &quot;Type of doggo&quot; %&gt;<br>  &lt;%= f.collection_select :type_id, Type.all, :id, :name %&gt;&lt;br&gt;<br>  &lt;%= f.submit %&gt;<br>&lt;% end %&gt;</pre><p>(If you’re curious, here is the resulting HTML that the Action View <a href="https://guides.rubyonrails.org/form_helpers.html">form helpers</a> above generated. The form won’t submit anything, but you can look at the HTML and visualize the form better!)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fjacjyd%2Fembed%2Fpreview%2FzYNqxgw%3Fheight%3D600%26slug-hash%3DzYNqxgw%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fjacjyd%2Fpen%2FzYNqxgw&amp;image=https%3A%2F%2Fassets.codepen.io%2F5107554%2Finternal%2Fscreenshots%2Fpens%2FzYNqxgw.default.png%3Ffit%3Dcover%26format%3Dauto%26ha%3Dfalse%26height%3D540%26quality%3D75%26v%3D2%26version%3D1616767666%26width%3D960&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/da953a3c547c6226a5090b6e320b5984/href">https://medium.com/media/da953a3c547c6226a5090b6e320b5984/href</a></iframe><p>If a user enters a name of “Hamstar”, chooses “smol pupperino”, and hits that submit button, here are the params that are returned to the server (the <a href="https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html">authenticity_token</a> will differ):</p><pre>params #=&gt; #&lt;ActionController::Parameters {&quot;authenticity_token&quot;=&gt;&quot;U2K2Nnolg8eGv0ayjnf_1yDUEu1kczoWibSNonUlhGviadr9Ia3uoYnomugheL_A9JtdmpGq3Q7dKnNakIZneA&quot;, <strong>&quot;dog&quot;=&gt;{&quot;name&quot;=&gt;&quot;Hamstar&quot;, &quot;type_id&quot;=&gt;&quot;2&quot;}</strong>, &quot;commit&quot;=&gt;&quot;Create Dog&quot;, &quot;controller&quot;=&gt;&quot;dogs&quot;, &quot;action&quot;=&gt;&quot;create&quot;} permitted: false&gt;</pre><p>Nestled in there are the values you need to create the dog!</p><p>You can also play around with hidden_tag/ hidden_field form helpers and buttons (tiny forms), too, to get and pass through the information you seek in your controller methods.</p><h4>Is params a hash? How do we use params data?</h4><p>Technically, paramsis not a hash, though it looks like one. As you can see above, params is actually an instance of<a href="https://apidock.com/rails/ActionController/Parameters">ActionController::Parameters</a>. We can interact with params largely like a hash and in fact, <a href="https://github.com/rails/rails/pull/20868">up until Rails 5.0</a>, ActionController::Parameters did inherit from the Hash class. As a different class, hashes have some familiar methods that params does not, such as #flatten, #each_key, #each_value, and #map.</p><p>But params has a few tricks of its own. Here are all the methods available to params that a hash can’t do.</p><pre>:permitted?, :to_unsafe_h, :to_unsafe_hash, :permit!, :converted_arrays, :permit, :require, :parameters, :permitted=, :fields_for_style?, :method_missing, :always_permitted_parameters, :always_permitted_parameters=, :init_with, :required</pre><p>There is a lot here having to do with safety and permissions! That’s because params are the conduit through which the unsafe internet/absent-minded user can send data to your controllers and possibly ultimately your database. And for best practices, you should use…</p><p><strong>Strong Params! </strong>🦾</p><p>You should be glad that params isn’t exactly a hash because there are two important methods to learn to use on them: #require and #permit. If you recall a little while ago, the params had this little value at the end: permitted: false. If you tried to use params[:dog] directly as you would with a hash to provide attributes to #create a new dog, you would have hit an “ActiveModel::ForbiddenAttributesError” (given standard settings). To allow form data to be used, you would have to do something like this:</p><pre># dogs_controller.rb</pre><pre>def dog_params<br>  params.require(:dog).permit(:name, :type_id)<br>end</pre><p>The #require method verifies that the params contains a key of and information about a dog. If params comes in without this dog key, most likely it’s form data from elsewhere, or data that isn’t useful to you to create or update an instance of theDogclass. The #permit method specifies which keys within dog to allow the values of. You could allow a user to change a dog’s name, for example, but not their type.</p><p>With these two methods performed on params, you can use it directly in creating your dog with :name and :type_id as attributes.</p><pre>dog_params #=&gt; #&lt;ActionController::Parameters {&quot;name&quot;=&gt;&quot;Hamstar&quot;, &quot;type_id&quot;=&gt;&quot;2&quot;} <strong>permitted: true</strong>&gt;</pre><pre>---</pre><pre>new_dog = Dog.create(dog_params)</pre><p>But other than that small feature, treat params as you would any other hash!</p><p><strong>…one more factoid before you leave</strong></p><p>Now this is for coding cocktail party chatter - did you notice that one of the params-only methods was #to_unsafe_hash? This would turn params into a <a href="https://apidock.com/rails/ActiveSupport/HashWithIndifferentAccess">hash with indifferent access</a>, which you can do anything to that you would with any old piece of nested data. Use your power wisely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BAg8nTqgo25zf6P3" /><figcaption>Photo by <a href="https://unsplash.com/@eli_j?utm_source=medium&amp;utm_medium=referral">Elias Castillo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I hope sharing what I may understand about params has helped you in some way. Please let me know if anything seems off, and then we’ll discuss and learn more!</p><p>Thanks to those involved in this exasperated <a href="https://stackoverflow.com/questions/6885990/rails-params-explained">Stack Overflow question</a> on what params are and <a href="https://stackoverflow.com/questions/34949505/rails-5-unable-to-retrieve-hash-values-from-parameter/34951198">this post</a> on params’ status as a hash or not, who all helped me sleep at night whether they know it or not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc8bbb6c150b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>