<?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 Ben Merchant on Medium]]></title>
        <description><![CDATA[Stories by Ben Merchant on Medium]]></description>
        <link>https://medium.com/@benmerchant?source=rss-6a827a815618------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mni-kDM2D_316FgfA7Haaw@2x.jpeg</url>
            <title>Stories by Ben Merchant on Medium</title>
            <link>https://medium.com/@benmerchant?source=rss-6a827a815618------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:25:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benmerchant/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[Day08 - #100DaysOfCode - Back in the Saddle]]></title>
            <link>https://medium.com/@benmerchant/day08-100daysofcode-back-in-the-saddle-4382eecee61a?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/4382eecee61a</guid>
            <category><![CDATA[linkedin-profile]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Wed, 20 Apr 2022 16:25:54 GMT</pubDate>
            <atom:updated>2022-04-20T16:25:54.475Z</atom:updated>
            <content:encoded><![CDATA[<p>After a bit of a hiatus (*cough* Elden Ring) I am back at it. I have a screening call with a recruiter today. The last one ghosted me. I’ve reached out and confirmed that we are on for our 2 PM call.</p><p>This job is a full stack position, and the backend is Django, which I have never used. So, I returned to my mentor, <a href="https://www.youtube.com/watch?v=rHux0gMZ3Eg">Mosh, on YouTube</a>, to get me up to speed.</p><p>I also complete ten more LinkedIn skills quizzes in an effort to raise my visibility on the site.</p><p>Here’s the brain dump for yesterday:</p><figure><img alt="Python Django" src="https://cdn-images-1.medium.com/max/750/1*lXIPkmgt_m-0WJpKLE80Xw.jpeg" /></figure><h3>Django</h3><ul><li>Other frameworks: Flask, Tornado, Bottle, Falcon, Hug</li><li>Batteries-included: Admin Site, ORM, Auth, Caching</li><li><em>pipenv: </em>dependency management tool. Installs our app dependencies in virtual environments. Our app deps will not clash with other app’s deps</li><li>to activate this project’s <em>virtualenv</em> run <em>pipenv shell<br></em>OR: run a command inside the virtual environment w/ <em>pipenv run</em></li><li><em>pipfile</em> is comparable to package.json</li><li>no one uses <em>django.contrib.sessions</em> any longer. Legacy app that uses temporary memory on the server to manage user data. Delete it.</li><li>We can create our own apps with<br><em>python manage.py startapp </em>[APPNAME]</li><li><em>apps.py</em> would be better named <em>config.py</em></li></ul><h4>Views</h4><ul><li>a <em>view</em> function takes a <em>request </em>and returns a <em>response<br>- </em>other frameworks call them <em>request handler </em>or <em>actions</em></li><li>not to be confused with what Django calls a <em>template</em> it is however often associate with what a user sees</li><li>example usages: pull data from a DB, transform data, send email…</li><li>add a <em>urls.py</em> — this is a conventional name, could be anything — to map URLs to our view functions</li><li><em>urlpatterns = [URL Pattern Objects] ← </em>using path function to create these<br>URL Conf module (not sure what this note means)</li></ul><h4>Using Templates</h4><ul><li><em>render() returns an HTTPResponse object</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*lXIPkmgt_m-0WJpKLE80Xw.jpeg" /></figure><ul><li>no one uses templates anymore</li></ul><h4>Debugging</h4><ul><li><em>launch.json</em> — add an argument to the args, the PORT so it doesn’t clash with the running :8000</li><li>// Thank God… after adding some routing, the homepage wouldn’t load. Mosh said it’s because we registered a custom route so we only see the homepage the first time we run a Django project. However, he didn’t say this until a few moments later, and I spent some time trying to get the homepage to load.</li></ul><h3>What’s Next?</h3><ol><li>Spin up a Django back end for BenMerchant.dev</li><li>Take AWS CLF-C01 Cloud Practitioner Certification Exam</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4382eecee61a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day07 - #100DaysOfCode - Redux]]></title>
            <link>https://medium.com/@benmerchant/day07-100daysofcode-redux-cc6481c3892b?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc6481c3892b</guid>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 13:25:47 GMT</pubDate>
            <atom:updated>2022-03-04T13:25:47.541Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Redux Thunk handles asynchronous actions</li><li>apply middleware by passing a second optional argument to createStore()</li><li>to create an async action return a function in the action creator that takes ‘dispatch’ as an argument. Within this function you can dispatch actions and perform asynchronous requests</li><li>common practice: dispatch an action before async actions so the application knows data is being requested. Maybe display a loading icon for the user</li><li>NEVER mutate state<br>NEVER modify sate directly<br>Instead, return a new copy of state</li><li>me: I used the spread operator, and the next lesson was how to use the spread operator. 10 points to Gryffindor</li><li>use Array.slice()with a spread operator</li><li>Object.assign() — copy an object</li></ul><h3>React &amp; Redux</h3><ul><li>React components subscribe to only the pieces of data in the store that are relevant to their role<br>- Then, you dispatch actions directly from React components which trigger store updates</li><li>Remember: use a key with Array.map()<br>You can bind this inline in the JSX</li></ul><h3>Today</h3><ul><li>Finish the React/Redux lessons</li><li>Start the Front End Development challenges</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc6481c3892b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day6 - #100DaysOfCode - Finish React, Start Redux]]></title>
            <link>https://medium.com/@benmerchant/day6-100daysofcode-finish-react-start-redux-a10dc4b0d618?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/a10dc4b0d618</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Tue, 01 Mar 2022 19:31:48 GMT</pubDate>
            <atom:updated>2022-03-01T19:31:48.388Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Good Morning! It’s the last day of February.<br>- a text from my Mama</blockquote><ul><li>inline style properties are assumed to be in ‘px’. To use ‘em’ or another unit, simply wrap in quotes ‘72px’</li><li>me: don’t return from class methods. setState() method</li><li>me: used an if/else before render() to determine which elements would display</li><li>{condition &amp;&amp; &lt;p&gt;markup&lt;/p&gt;}</li><li>use ternaries directly inside JSX code</li><li>use props to conditionally render code</li><li>When you set a style object based on a conditional, you describe how the UI should look as a function of the application&#39;s state. There is a clear flow of information that only movies in one direction.</li><li>use Array.map() to iteratively display child elements<br>must use Array.map() with a ‘key’ which must be unique between siblings but not globally</li></ul><h3>Redux</h3><ul><li>Redux is a state management framework that can be used w/ myriad different technologies.</li><li>The Redux Store is the single source of truth for the entire app. Any piece of the app that wants to update state must do so via the Redux Store.</li><li>const store = Redux.createStore(reducer)</li><li>const store = Redux.createStore( (state=foo) =&gt; state )</li><li>All state updates are triggered by dispatching actions, JS objects that contain info about an action event that has occured<br>- somtimes carry data (optional)<br>- (required) <em>type </em>property that specifies the type of action that occured<br>- Action Creator — JS function that returns an action. Creates objects that represent action events</li><li><em>store.dispatch() — </em>dispatches actions tot he Redux store. pass the returned value from the action creator. sends the action back to the store</li><li>reducers — responsible for state modifications that occur in response to actions. takes <em>state</em> and <em>action </em>as arguments. Always returns a new state.</li><li>use Redux store to manage multiple action types<br>ie… different state representations for when users are logged in/out</li><li>Common practice to assign action types as read-only constants then reference these constants when needed</li><li>Redux.store.subscribe() — subscribes listener functions to the store, which are called whenever an action is dispatched against the store.</li></ul><h4>The First Principle of Redux</h4><blockquote>All app state is held in a single state object in the store</blockquote><ul><li><em>combineReducers() </em>accepts an object as an arg in which you define properties which associate keys to specific Reducer functions.</li></ul><p>Only six Redux lessons left. Then 10 React/Redux lessons.</p><p>I keep coming back to wanting to be down on myself for not making more progress more quickly. I’m comprehending this material, though. Writing things down with pen and paper really help. Transferring those notes here helps. What I need to do is summarize/review all of the material at some point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a10dc4b0d618" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day05 - #100DaysOfCode - Slow Weekend]]></title>
            <link>https://medium.com/@benmerchant/day05-100daysofcode-slow-weekend-5f7290992243?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f7290992243</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Mon, 28 Feb 2022 13:49:53 GMT</pubDate>
            <atom:updated>2022-02-28T13:49:53.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Treating Saturday and Sunday, collectively, as day five. Finished a few of the lessons. Plan to finish them today.</p><ul><li>You can pass handler functions, or any method defined on a React component to a child company. Pass it just like a regular prop. Access it with ‘this.prop’</li><li>me: got stuck for the better part of a half hour because I was passing the handler method as ‘onChange’</li></ul><h3>Lifecycle Hooks</h3><ul><li>componentDidMount() — best practice to place API calls here. best place to attach any event listeners you need to add for specific functionality<br>- React provides a synthetic event system which wraps the native event system. This ensures consistent behavior across various browsers<br>- If you want to attach an event handler to the ‘document’ or ‘window’, you must do this directly</li><li>me: got stuck again because of a typo in a method designation</li><li>React re-renders any component (and its children) any time it receives new ‘state’ or ‘props’</li><li>shouldComponentUpdate() — not in Most tutorial, must be new<br>- return a boolean<br>- compare the props to determine if the component should update</li></ul><p>As I said, it was a slow weekend, but I am still motivated by forward progress. Today I <strong>will</strong> finish the React section on freeCodeCamp and hopefully move on to the Redux section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f7290992243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day04 - #100DaysOfCode - React State]]></title>
            <link>https://medium.com/@benmerchant/day04-100daysofcode-react-state-fc8df79257d5?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc8df79257d5</guid>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Sat, 26 Feb 2022 14:40:59 GMT</pubDate>
            <atom:updated>2022-02-26T14:40:59.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*JJ4av8JzQtjxriv796KseA.png" /></figure><p>Yesterday I knocked out a few more React lessons on freeCodeCamp. The concepts are mostly those that I’ve already seen, just explained differently.</p><ul><li>this.setState({state props: updated state data})</li><li>React never expects you to modify state directly.</li><li>React may branch multiple state updates to improve performance<br>ASYNCHRONOUS (there is a way around this should the need arise)<br>* <em>when would this need arise?</em></li><li>Explicitly bind ‘this’ to a class method in the constructor so it becomes bond to the class method when the component is initialized.</li><li>LEARN — do a deep dive on ‘this’</li><li>Using a function with ‘setState()’ guarantees you are working with the most current values of state and props.</li><li>HTML element visibility toggling using conditionals in the render method</li></ul><h4>Controlled Input</h4><ul><li>Form control elements [input]/[textarea] maintain their own state in the DOM as the user types</li><li>You can move this mutable state into a React component’s state</li><li>React controls the value of that input field</li><li>When you type in the box, that text is processed by the handleChange() method set as a property in the local state</li></ul><blockquote>DON’T FORGET TO BIND ‘this’!!!</blockquote><h4>Unidirectional Data Flow</h4><ul><li>State flows in one direction… Down… parent -&gt; child</li><li>State management is handled by one part of the app and UI rendering by others</li></ul><h3>17 React Lessons Left</h3><p>My goal today is to finish the React lessons on FCC today. After that there are 27 involving Redux, which I assume is state management like VueX. Then there are five projects that I’ll have to make a section for on <a href="https://benmerchant.dev/">BMDD</a>.</p><p>Sometimes I feel like I should be working faster or better. Then I remember that I am working. That consistent forward progress is the key!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc8df79257d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day03 - #100DaysOfCode - LinkedIn to State]]></title>
            <link>https://medium.com/@benmerchant/day-03-daysofcode-linkedin-to-state-d52185329c1a?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/d52185329c1a</guid>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 16:37:15 GMT</pubDate>
            <atom:updated>2022-02-26T14:13:27.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*grOwWyGHxFL5PKMLej2NgA.png" /></figure><h3>LinkedIn</h3><p>Was surfing LinkedIn yesterday and applied for a job at a FinTech firm. They had emojis in the listing which is a double edged sword for me. It let’s me know they are ran by millennials, but I tend to get along swimmingly with people from previous generations in positions of power.</p><p>While on the site, I took the CSS skill assessment. I abhor CSS and its myriad imperfections (ironic, I know, considering my affinity for JavaScript). Scored in the top 5% of examinees. Here’s to hoping my next job doesn’t need me for my styling abilities.</p><h3>freeCodeCamp - React</h3><p>This is still overlapping the Mosh tutorial. It’s heartening to start to ‘get tired’ of seeing the same things in lessons. It’s working.</p><ul><li>Child components can accept arrays as props (I assume this is preparing us for using objects as props to encapsulate data as Mosh taught us).</li><li>DefaultProps can be used to specify a value should none be explicitly provided</li><li>FUN FACT: FCC had a typo in the lesson on overriding default props. The instructions said the data should be ‘100’, but the tests were looking for ‘10’.</li><li>React can check the PropTypes and isRequired. Nowadays, you must import ‘prop-types’ independently of React.</li><li>Stateless functional components act like pure functions. They will return the same JSX given the same props.</li><li>Stateless Functional Component — any function which accepts props and returns JSX<br>Stateless Component — extends React.Component but does not use internal state<br>Stateful Component — class component that does maintain its own internal state</li><li>A common patter is to minimize statefulness and create SFCs wherever possible. This makes it easier to follow how changes to state affect app behavior.</li><li>Create state by declaring a ‘state’ property on the component class in its constructor.</li><li>Remember: if you make a component stateful, no other components are aware of its ‘state’. Pass state data to children via props.</li></ul><blockquote>Question for the teacher: what are sometimes you’d want to encapsulate a new state in a child component?</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d52185329c1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day02 - #100DaysOfCode - React, Portfolio, LeetCode]]></title>
            <link>https://medium.com/@benmerchant/day02-100daysofcode-react-portfolio-leetcode-96962dea7ea3?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/96962dea7ea3</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 18:14:03 GMT</pubDate>
            <atom:updated>2022-02-24T18:14:03.155Z</atom:updated>
            <content:encoded><![CDATA[<p>It occurred to me that it would be more fitting to post in the mornings to more closely resemble a standup meeting. Admittedly, there is another reason, I wait tables 5–6 nights a week, and the time we get off isn’t particularly conducive to writing well-thought out posts. So, without further ado:</p><h3>React</h3><p>I completed seven lessons in the React section of FreeCodeCamp’s front end library curriculum. A lot of it overlapped what I had learned the day before, which helped the info settled further into my deep brain. Some notes:</p><ul><li>Stateless Functional Component<br>- CAN receive data<br>- CAN render data<br>- CANNOT track data<br>- CANNOT manage data</li><li>React requires function name to begin with a capital letter</li><li>Class Component — best practice to call a component constructor with super and pass props to both to ensure proper initialization.</li><li>Components — when React encounters a custom HTML tag that references another component, it renders the markup for that component in the location of the tag. <br>* me: <em>this hearkens back to the library’s lifecycle hooks and the recursive method by which it renders nested components.</em></li></ul><h3>Ben Merchant dot dev</h3><p><a href="https://benmerchant.dev/">My Site</a> is up and running again. It looks like this right now (for posterity):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqhM7w6ltTMho1ckveX8QA.png" /><figcaption>BMDD v1.0</figcaption></figure><p>This was created with React. I have been <a href="https://github.com/benmerchant/bmdd/issues">creating issues</a> and knocking them out myself as a way to both git back in the habit and track my progress. I should note here (and on the site eventually) that I am not a designer and have no plans to do any designing outside of using Bootstrap templates (yet).</p><p>Endgame: an endless scroll of blogposts, an about me page, projects section</p><h3>LeetCode</h3><p>If you ever start to lose that imposter syndrome feeling, boy oh boy, do I have a website for you. <a href="https://leetcode.com/benmerchant/">LeetCode</a> provides over two thousand programming problems that I have been told look great on your resume. I completed two of the easy ones. It’s completely brilliant, except for one process I don’t understand.</p><blockquote>Question: How does one list their LeetCode on their resume?</blockquote><p>When you finish a problem you can <strong>Run Code</strong> to test it, then you click <strong>Submit</strong>. In my head I’m comparing these to <strong>npm run tests</strong> and <strong>git push</strong> (to remote) respectively. I would never push my local code if it didn’t first pass the testing suite. When you click submit on LeetCode, it (sometimes?) runs additional tests that your subpar algorithm wasn’t subjected to initially. After this you are permanently marked with a not accepted submission, lowering your acceptance rate. I’m more than sure that potential employers are more interested in seeing you try and why you thought your failures would work. I just wanted to keep it 100.</p><blockquote>True Story:<br>Interviewer: What is your biggest weakness programmingwise?<br>Me: I’ve been doing so much web devving with Angular and Express’s sugary syntax that I fear I’m losing my JavaScript algorithm solving abilities.<br>Interviewer: Well, good thing this is a web dev job.</blockquote><h3>What are you doing today?</h3><p>Not much time before work, so I’ll try to knock out as much of the FCC React lessons as possible. If I need a break, I’ll start on a BMDD issue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96962dea7ea3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day01 - #100DaysOfCode - React Tutorial for Beginners]]></title>
            <link>https://medium.com/@benmerchant/day01-100daysofcode-react-tutorial-for-beginners-3a7fdde7c286?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a7fdde7c286</guid>
            <category><![CDATA[mosh]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Wed, 23 Feb 2022 05:07:27 GMT</pubDate>
            <atom:updated>2022-02-23T05:07:27.257Z</atom:updated>
            <content:encoded><![CDATA[<p>These are notes I recorded while taking <a href="https://www.youtube.com/watch?v=Ke90Tje7VS0">this YouTube tutorial</a>. While, just like in a college course, these are directly from the instructors mouth, I will attempt to combine, paraphrase, restructure in such a way as to both explain and further cement to memory what I have just learned. These are not meant to be complete, polished writings, rather daily brain dumps.</p><p><a href="https://github.com/benmerchant/react-counter-mosh">Here’s my final GitHub repo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*61mO12J0AUIoDaKXWbhKeg.png" /></figure><h3>React Basics</h3><p>React is a JavaScript library that uses JSX, a simple syntax, to control the View of a web app. Unlike Angular, which is a full templating engine that manages the Model, View, and Controller. As such, there are certain limitations which come with their own workarounds.</p><p>There are no concepts of loops nor If/Else conditional statements. We can, instead, use Array.map() to loop through arrays. This done inside curly braces.</p><p>Warning: each child in a list should have a unique ‘key’ prop</p><ul><li>EXPAND: strict mode restricts THIS usage</li><li>whenever you need to pass an argument to event handlers, pass an inline arrow function</li><li>PROPS include data that we pass to a component<br>STATE includes data that is local/private to that component</li><li>the component that owns a piece of the state should be that one modifying it. <br>pass a method to modify the state down to child components</li></ul><blockquote>child raises the event<br>parent handles it</blockquote><ul><li>if the key and value are the same, you only need to send the name once</li><li>JAVASCRIPT: The whole point of objects is to <strong>encapsulate</strong> related values</li></ul><h3>Single Source of Truth</h3><p>I learned this term at my last job while using Vue. To me, the state is sacred. This would appear to be React’s take on it as well considering how well it’s protected.</p><p>If a component is being controlled by a parent, then it doesn’t have its own local state. Instead, it receives all of its data via props and raises events whenever data needs to be changed. Since there is no local state, it doesn’t make sense to have the methods controlling the data in the controlled component.</p><blockquote>Remember, the child <em>raises </em>events</blockquote><p>Whenever you want to keep two sibling (no parent/child relationship) components in sync, you must <em>lift the state up</em>.</p><ul><li>LEARN: attempted to refactor a class component to a stateless functional component but got an error that it couldn’t read the props… undefined… This happened because I didn’t watch the next fifteen seconds of the video</li><li>JAVASCRIPT: Destructure arguments</li></ul><h3>Lifecycle Hooks</h3><p>There are three phases of component creation. Each phases has one or more hooks. Each hook happens in order in each phase respectively. There are more than mentioned here, but they are rarely used.</p><ol><li>MOUNT<br>1.1. constructor() — only called once when an instance of a class is created. Good time to initialize the properties. one use case is to set the state based on the props from the outside. Don’t call setState() in the constructor or it will throw an error. This is because this method can only be called when (after?) a component is rendered and placed in the DOM. You must set the state directly here.<br>1.3 componentDidMount() — called after component is rendered into the DOM. Perfect place for AJAX calls. First a parent is rendered, then its children are rendered recursively. You CANNOT use lifecycle hooks in stateless functional components. Only with Class components</li><li>when entire component tree is rendered, this doesn’t mean the actual DOM is re0rendered. When a component is rendered, you basically get a React element. That updates the Virtual DOM. React has a copy of the old Virtual DOM and only updates what has chagned<br>2.2 componentDidUpdate() — called after an update. compares old state/props to new ones and only if there are changes should we make an AJAX call. O P T I M I Z A T I O N.</li><li>Good opportunity for cleanup to avoid memory leaks. timers, listeners, etc…</li></ol><h4>Review</h4><ol><li>Props — pass data to components</li><li>Raising and Handling Events</li><li>Lifting the state — multiple components sharing the data and remaining in sync. Single Source of Truth</li><li>Functional Components</li><li>Lifecycle Hooks</li></ol><p>I added a button after the tutorial to add a counter, and it was surprisingly easy and worked the first try.</p><ol><li>create ADD button in counters.jsx with onClick={onAdd}</li><li>add prop to &lt;Counters /&gt; map loop in App.js onAdd = {this.handleAdd}</li><li>create handleAdd() in App.js</li></ol><h3>Conclusion</h3><p>I searched my GitHub repos for ‘React’ and found four, the earliest of which dates back three years. (This doesn’t count the few I’ve deleted over the years). All of them remain unfinished save this one.</p><p>What’s next?</p><p>A large issue facing burgeoning intermediate developers isn’t ‘how to code’ but rather ‘what to code’. As such, I will be going through the FreeCodeCamp Front End Development curriculum. I cleaned up everything before React, Bootstrap, Sass, etc) and have done half a dozen of the lessons in the React section.</p><p>I was so excited from coding so much today, that I threw up a quick blog outline with React and officially restarted<a href="https://benmerchantdotdev.netlify.app/"> Ben Merchant Dot Dev</a> back up. Granted all the DNS stuff isn’t completed yet, its still a vanity URL on Netlify.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a7fdde7c286" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create and Test a Node.js Blog API]]></title>
            <link>https://medium.com/@benmerchant/how-to-create-and-test-a-node-js-blog-api-819170280abd?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/819170280abd</guid>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Mon, 11 Jun 2018 19:18:56 GMT</pubDate>
            <atom:updated>2019-06-18T13:46:18.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdo0UBpyszvD7-7EH4TkIA.png" /></figure><h4>Update: June 18, 2019:</h4><p>Turns out that, yes, this will teach you how to spin up a Node API. However, since publishing, I’ve learned how to better separate my concerns or ensure that each component has a ‘single responsibility’. (<a href="https://en.wikipedia.org/wiki/SOLID">The ‘S’ in SOLID</a>) As such, I hope to publish a ‘correction’ story’ in one week’s time.</p><p>I look forward to learning with you.</p><p><em>[Unedited original text after the fold.]</em></p><p>I’m in the process of designing <a href="https://benmerchant.github.io/">my own portfolio website</a> from scratch with no templates or frameworks. Ostensibly, every website needs a blog section to let visitors know the state of things. I thought it’d be nice to blog about my blog (meta) and hopefully help someone else learn a bit about Node.js.</p><p>Things you <em>must</em> know beforehand:</p><ul><li><a href="https://www.json.org/">What JSON is</a></li><li>How to enter commands into the shell (command line)</li><li>Basic JavaScript syntax and terminology (ES6 a plus, if not you’ll pick it up)</li></ul><p>Things you must do first:</p><ul><li><a href="https://nodejs.org/en/download/">Install Node</a></li><li><a href="https://docs.mongodb.com/manual/installation/">Install MongoDB</a></li><li><a href="https://git-scm.com/downloads">Install Git Bash</a> (optional)</li></ul><p>What we won’t do in this tutorial: write any HTML (we’ll cover that in a future post). We will be designing back end API. It will handle HTTP requests from the browser (or Postman, or our tests) and respond with data from our database and whatever else we want to say. This is a web-server or a web-service. You could give someone the documentation to your API and they could create their own website or mobile app using your service.</p><p>I’m using Node.js version 8.11.1. I’m sure it will work in future versions. But might not in previous versions.</p><p>If you want to see the finished code, <a href="https://github.com/benmerchant/portapi">go to the repo here</a>.</p><p>I always start with a brand new GitHub repo. Go to yours and create one. Call it whatever you want. Do NOT initialize the repository with a README. For this tutorial we’ll call it “portapi” as it is an api for my portfolio. I struggled over whether or not to include Git in this tutorial and decided to do so as a way to make this a little closer to an intermediate tutorial as opposed to the plethora of beginner code-alongs.</p><p>Open your command prompt and navigate to wherever you like to develop apps. We need to create a brand new directory.</p><pre>$ mkdir portapi</pre><p>Don’t type any dollar signs you see in code snippets. They represent the Git bash command prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*wrAic2ls0ldFxpA26hWftQ.png" /><figcaption>Don’t type the ‘$’ sign.</figcaption></figure><p>Now move into your new directory.</p><pre>$ cd portapi</pre><p>Next, enter these commands to create a README file. Initialize your new local directory as an empty Git repository. Stage the README to me committed. Record the changes with the a commit message. Add a new remote</p><pre>$ echo &quot;# Hello, portapi!&quot; &gt;&gt; README.md<br>$ git init<br>$ git add README.md<br>$ git commit -m &quot;first commit&quot;<br>$ git remote add origin https://github.com/&lt;YOUR_GITHUB_NAME&gt;/portapi.git<br>$ git push -u origin master</pre><p>Go back to your repo on Github. It should have the README in it and say “Hello, portapi!”. I have gotten in the habit of doing this every time I start anything project. Note: you will have to enter your GitHub credentials to proceed. <a href="https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage">I stored mine to Git Bash.</a></p><p>Back in the command line type.</p><pre>$ npm init</pre><p>This begins the process of creating a package.json file for our project. Just hit enter for every prompt except for <em>entry point</em>. Type in “server.js”. Why? It doesn’t matter too much, but I like to think that this is a web-server, not a fully fledged app. Even though I’ll call it an app sometimes.</p><p>Go to your text editor (I like Atom) and open the newly created package.json. We are going to add some dependencies. Some people prefer to install dependencies on the command line. Sometimes, I do too. But for a project like this, I prefer to add them to the package.json and install them all at once. After the last field (mine says homepage, yours will be different if you didn’t git init), add the following fields.</p><pre>&quot;dependencies&quot;: {},<br>&quot;devDependencies&quot;: {}</pre><p>Dependencies are other Node packages that are necessary for your app or package to work. DevDependencies are packages that help you develop the app and are not necessary for your app’s functionality. Next, we’ll fill these two objects with everything we’ll need starting with the DevDependencies.</p><pre>// package.json<strong><br></strong>&quot;devDependencies&quot;: {<br>    &quot;chai&quot;: &quot;4.1.2&quot;,<br>    &quot;chai-http&quot;: &quot;4.0.0&quot;,<br>    &quot;mocha&quot;: &quot;5.1.1&quot;,<br>    &quot;nodemon&quot;: &quot;1.17.3&quot;<br>}</pre><p>What are these packages that we need to develop our app? The first three are for testing purposes. I’ve come to believe that automating tests from day one/line one makes everything simpler later. And you won’t need to download Postman (even though you should).</p><p>Nodemon is a module that will automatically restart your server every time you hit CTRL + S (which should be frequently).</p><p>Let’s get our core modules installed now.</p><pre>// package.json<br>&quot;dependencies&quot;: {<br>    &quot;body-parser&quot;: &quot;1.18.2&quot;,<br>    &quot;express&quot;: &quot;4.16.3&quot;,<br>    &quot;mongoose&quot;: &quot;5.0.16&quot;<br>}</pre><p>Express.js is a Node.js web framework. It will do all of the heavy lifting of handling HTTP request for us [POST, GET, PUT, DELETE]aka [CREATE, READ, UPDATE, DELETE]. Some people like to start with read, but how can you read what has not yet been created?</p><p>We need “body-parser” to get the body of incoming HTTP POST requests. Is there a way to do this without body-parser? Yes. We could also write this without Express at all, but I am not well-versed enough to be writing about it. Remember, these modules are just collections of functions someone wrote. You could write your own functions the same way you could write your own web environment in C++. But, what would <a href="https://www.youtube.com/watch?v=zGxwbhkDjZM">Sweet Brown</a> say about that?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*ntWOsBb93dLmYIbsyYE52A.jpeg" /></figure><p>Mongoose is an Object Document Mapper for MongoDB. It handles the type casting and validation we will want for our blog. You could check out <a href="https://github.com/express-validator/express-validator">express-validator</a> if you like. We could use it later, but that will be a chance to write one simple function instead of requiring another package.</p><p>You may see some <em>package.jsons</em> and notice that the version numbers are prepended with <a href="https://stackoverflow.com/a/22345808">carats (^) or tildes (~)</a>. We are going to omit these in order to force our app to always use the same version. That way if it works today, it will work tomorrow, period</p><p>Let’s install our packages. Go back to your command line and type</p><pre>$ npm install</pre><p>This will install 334 packages. That sounds like alot, it is. But this is the most basic plan I could come up with. It’s a little less than 15 MB.</p><h3>It’s Coding Time</h3><p>In the command line type:</p><pre>$ touch server.js</pre><p>You could also just create a new file in your editor, but this is simpler. Go to your editor and open this new server.js and type:</p><pre>// server.js<br>console.log(&#39;Hello Node&#39;);</pre><p>I like to make sure thing’s are working from time to time. The beginning seems like a good time. We are going to run our new app. Save server.js and go back to the command line and type</p><pre>$ nodemon</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*RGsnLIpL6oMRz3ZoXWqV3A.png" /><figcaption>Well, hello to you too.</figcaption></figure><p>Remember when we changed the entry point when we ran npm init? Since we named it <em>server.js</em> and the file containing the ‘Hello Node’ <em>console.log()</em> is called <em>server.js</em>, Nodemon knows to “enter” our app in this file. Nodemon is still running, still listening for changes to our app. Go back to <em>server.js</em> and add another <em>console.log()</em> and save the file. Check your command window.</p><p>Nodemon recognized that we changed a file and automatically restarted our server. You should see “Hello Node” and whatever your new <em>console.log()</em> said. If it didn’t work. Try again. Don’t move on until it does. Remember to remove both console logs and have a blank <em>server.js</em> before we move on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*vYOMxio2LEKKqk3xzboPtQ.png" /><figcaption>Just in case there is any confusion on what your code should look like at this point.</figcaption></figure><h4>Some modules required</h4><p>We “installed” the modules we’ll need. But that simply means that we downloaded some files from npm to our local machine. Our app has no idea what packages we want to use. It doesn’t know anything at this point. Let’s include them. (Include, require, import: tell one file to use other files)</p><pre>// server.js<br>const bodyParser = require(&#39;body-parser&#39;);<br>const express = require(&#39;express&#39;);<br>const mongoose = require(&#39;mongoose&#39;);</pre><p>Now all of the functions in those three modules are available to <em>server.js</em>. But how do we get to the API itself? We need to set it up so that we can navigate to it on a port. <a href="http://lmgtfy.com/?q=what+are+ports+computer+networking">What are ports?</a></p><p>Underneath the require statements type</p><pre>// server.js<br>const app = express();</pre><pre>app.listen(8080, err =&gt; {<br>  if(err) console.error(err);<br>  console.log(&#39;Server listening on port 8080...&#39;);<br>});</pre><p>The first line actually creates (initializes) our application by calling the express function we required above. The variable name <em>‘app’</em> is a convention, and I strongly recommend you follow it. Every tutorial and stack overflow answer will use it as well as the <a href="https://expressjs.com/en/4x/api.html">Express docs</a>.</p><p>The next bit is a function that listens for connections on the port we specify. In this case 8080. After the port number we have a callback function. I’m using ES6 arrow functions for this tutorial. Learn them. Learn ES6 in general. I’ll expound on that in a future post.</p><p>In the arrow function we are handling any errors that may occur by logging them to the console. The <em>console.log()</em> is just for our peace of mind. It’s nice to know that everything is working. Save your <em>server.js</em>. Since I never told you how to stop nodemon, it should still be running. It should have detected the changes we just made and look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*bBR7uvehmH1f6bvHwphnWg.png" /><figcaption>Take a break to call your mother and let her know you just coded your first server.</figcaption></figure><h4>Handle your routes</h4><p>Now we are going to stop are server to create some more files. In your command prompt window press CTRL + C. No, it doesn’t copy anything to clipboard, but I guarantee you’ll try to use it as such in the future and have to restart your server. I still do. (To copy in Git Bash you press CTRL + INS).</p><p>Our server is no longer listening and we are once again able to enter commands into the prompt. We are going to go ahead and create all of the files and directories we’ll need for our blog. Enter all of these commands and we’ll walk through them.</p><pre>$ mkdir app<br>$ cd app<br>$ touch config.js<br>$ touch router.js<br>$ mkdir controllers<br>$ cd controllers<br>$ touch blogpost.controller.js<br>$ cd ..<br>$ mkdir models<br>$ cd models<br>$ touch blogpost.model.js<br>$ cd ../..<br>$ mkdir test<br>$ cd test<br>$ touch blogpost.test.js<br>$ cd ..</pre><p>What did we just do? We created an <em>app </em>directory to hold the nuts and bolts of our app. In that directory we created two files: <em>config.js</em> and <em>router.js</em>. We also nested two directories in the app directory: <em>controllers </em>and <em>models</em>. In the <em>controllers </em>directory we created <em>blogpost.controller.js</em>. In the <em>models </em>directory we created <em>blogpost.model.js</em>.</p><p>Finally, we created a test directory in the root directory and created the <em>blogpost.test.js</em> file in it. You could argue that the test directory and file are optional, and I would argue you are wrong.</p><blockquote>We test first. We test often.</blockquote><p>Make sure you are back in the root directory and start your server again. Remember how? If not, the answer is type “nodemon”.</p><h4>config.js</h4><p>Look at the <em>app.listen()</em> method in server.js. Do you notice something ugly? Something ‘wrong’?</p><p>We hard-coded the port numbers. This is taboo in development. It’s not technically wrong. I mean, hey, it works right. But if we are just going to hard code data, then why are we creating an API in the first place? Why not hardcode our posts in HTML files?</p><blockquote>Because it’s inefficient and sloppy.</blockquote><p>I don’t want to maintain an indefinite number of HTML files. I’d rather download over 3600 files from a <a href="https://www.npmjs.com/">npmjs.com</a> and write a hundred lines of code so that in the future I can sit back on the beach, open a form, and publish a blog post in minutes.</p><p>The <em>config.js</em> file is where we will store our port number. We could just make it a variable in <em>server.js</em>, but in the future we might want to add a number of other configuration options. If/when that day comes, we have a nice place to do it.</p><p>Let’s open <em>config.js</em>, create an object, and export it. Trigger warning: excessive code for our purposes, but I’m assuming you plan on doing more than write one simple API.</p><pre>// config.js<br>const config = {<br>  port: process.env.PORT || 8080,<br>  db: &#39;mongodb://localhost/myblog&#39;,<br>  test_port: 4242,<br>  test_db: &#39;mongodb://localhost/myblog_test&#39;<br>}</pre><pre>module.exports = config;</pre><p>‘port’ and ‘test_port’ are ports we want our server to listen on. You may recognize the 8080 we used earlier. This is the port that will be utilized on our local machines. The 4242 is for testing purposes and will be used after we create our first route.</p><p>What about the ‘process.env.PORT’ variable. This is for when we host our API later on AWS (or Google, Heroku, etc). Somewhere in the dizzying myriad of settings you choose when you launch your app, you can set environment variables. One of these variables is the port you want to use. If you don’t set that port, our app will ‘default’ to 8080. The ‘||’ means ‘OR’ in JavaScript, but you already knew that.</p><p>‘db’ and ‘test_db’ are the locations of our local MongoDB instance. You did install MongoDB right? In a future tutorial we will connect with MongoDB’s cloud-based Atlas service (the url is literally …/cloud/atlas, we dev’s are not a glum lot). For now, we are going to do everything locally. We need to use a separate database for our tests because our tests will be completely emptying the database every time we run a test.</p><p>Lastly, we export the object as a module to be used in server.js.</p><p>Speaking of <em>server.js</em>, let’s go back to it and give the<em> app.listen()</em> method a makeover as well as import the config module we just created.</p><pre>// server.js<br>const config = require(&#39;./app/config&#39;);</pre><pre>app.set(&#39;port&#39;, config.port);<br>app.listen(app.get(&#39;port&#39;), err=&gt;{<br>  if(err) console.error(err);<br>  console.log(`Server listening on port ${app.get(&#39;port&#39;)}...`);<br>});</pre><p>First we import our config module. You may notice that we didn’t include the ‘.js’ in the config file name. You don’t have to. Node.js knows what you mean.</p><p>We set the port of the app to that from <em>config.js</em>. We didn’t have to call it<em> ‘port’</em>. We could have called it <em>‘thePortIWantToUseForMyApp’</em>. Express doesn’t care. Node doesn’t care. But I care. I really do. So let’s just call our port <em>‘port’</em>.</p><p>You’ll see in <em>app.listen()</em> we are now ‘getting’ the port we just ‘set’. We could have just used <em>config.port</em> here, but then you wouldn’t have learned about <em>app.set()</em>. Look at the<em> console.log()</em>. <strong>Notice </strong>that we are no longer using single quotes. We switched to backticks in order to implement ES6 template literals. We used a dollar sign followed by our <em>app.get()</em> in curly brackets. This will work for any variable. <em>Note: This won’t work in every browser as ES6 adoption isn’t universal, but we aren’t in the browser are we?</em></p><p>Your server should still be running. Assuming you’ve saved <em>config.js</em> and <em>server.js</em>, it should have restarted and logged the <strong>exact same message </strong>it did before. A common error here would be to not switch from single quotes to backticks.</p><h4>blogpost.model.js</h4><p>As with almost any file or variable in this tutorial, you are free to use whatever names you want. The ‘.model’ is completely superfluous. It’s redundant even. The file is <em>in </em>the models directory for Pete’s sake. But using this naming convention removes all ambiguity about what type of file your editing in the future. Consider a future where you have dozen of directories and hundreds of files. You’ll thank me then. Open it up and type this</p><pre>// blogpost.model.js<br>const mongoose = require(&#39;mongoose&#39;);<br>const Schema = mongoose.Schema;</pre><pre>// BlogPost Schema<br>const BlogPostSchema = mongoose.Schema({<br>  url: {<br>    type: String,<br>    required: true,<br>    unique: true<br>  },<br>  title: {<br>    type: String,<br>    required: true<br>  },<br>  body: {<br>    type: String,<br>    required: true<br>  },<br>  date: {<br>    type: Date,<br>    default: Date.now<br>  },<br>  tags: [String],<br>  updated: {<br>    type: Date<br>  }<br>});</pre><pre>module.exports = mongoose.model(&#39;BlogPost&#39;, BlogPostSchema);</pre><p>First we import mongoose then initialize the <em>mongoose.Schema</em> constructor as ‘<em>Schema</em>’. This constructor is how we will ‘model’ or define the format of our MongoDB documents. These first two lines will be the same in any model file.</p><p>The next declaration is the instantiation of a new model. I kept it as simple as possible, so we are only going to see two different data types, String and Date. These are JavaScript native types. Notice that some are required and some are not, this will help with our validation later on.</p><p>We also made ‘url’ unique. This is because we don’t want any confusion when someone permalinks or manually enters the url to a blog post they like and want to check later. We defaulted the ‘<strong>date ’</strong>(in this case it is the date the post was published) to Date.now. This means whenever we add a blog post to the database the current UNIX timestamp will be saved in our database. ‘<strong>Tags</strong>’ is an array of strings. We will be able to add as many as we like, as long as its not in the millions, in which case that would put a document over the 16 MB limit.</p><p>The last line does two things. The right half of the equals sign is making a copy of ‘BlogPostSchema’ and we are telling Mongoose that the MongoDB collection where we want to store blog posts is called BlogPosts. The collection name will be plural, but we give it as singular name that we will use to instantiate new blog posts. It handles the interpretation automatically. The left side of the equals sign is exporting our model to the rest of the app. This is a Node.js object.</p><h4>blogpost.controller.js</h4><p>Now we have a model for all blog posts that will be added to our MongoDB database. We know that every post will have the same format so that when we write the front end, we can be confident that no matter which post we pull to display on our site, it will be set up in the same way. Every post will definitely have a url, title, body, and date. They may or may not have tags. Posts may never be updated, but if they are, we have a place to store the time it happened.</p><p>We now need to define the instructions for what our API needs to do when we send it data from the browser (or a test or Postman). Here is some code. We’ll add more later for different CRUD operations, but for now, we just want to POST (HTTP verb) posts (blog posts).</p><pre>// blogpost.controller.js<br>&quot;use strict&quot;<br>const BlogPost = require(&#39;../models/blogpost.model&#39;);</pre><pre>// create a new Blog Post<br>exports.publishPost = (req, res) =&gt; {<br>  const NewBlogPost = new BlogPost(req.body);<br>  NewBlogPost.save((err, blogPost) =&gt; {<br>    if(err) {<br>      return res.status(422).json({<br>        msg: &#39;Server encountered an error publishing blog post.&#39;,<br>        error: err<br>      });<br>    }<br>    else {<br>      return res.status(200).json({<br>        msg: &#39;Successfully published blog post.&#39;,<br>        blogPost: blogPost<br>      });<br>    }<br>  });<br>};</pre><p>We start with a “use strict” expression. This tells our app to run in strict mode. At it’s most basic, this prevents us from doing certain things like using undeclared variables, duplicating parameter names in function definitions, and duplicating a property name in an object literal. Not that I would let you make any of these mistakes, but there are times you want to use this mode. This is one of those times. The controller is arguably the most important part of our app. It is defines all behaviors for our CRUD operations.</p><p>We then import our model.</p><p>Next we define a function that will be immediately exported. ‘req’ and ‘res’ are conventions in Node.js to represent the request and response objects. You can rename them, but why confuse your future self for the sake of contrarianism.</p><p><strong>Request </strong>is data coming from the user (GET, POST, etc…)</p><p><strong>Response </strong>is what the web-service will send back</p><p>All of the data about a new post will be in the body of the request object. Express tidies this up for us into a neat object named <em>req.body</em>. We assign that to a new object called <em>NewBlogPost</em>. We construct this new blog post using the model ‘<em>BlogPost</em>’ we just imported at the top of the script.</p><p>Everything else is one function. It is the <em>Model.save()</em> method. We are only going to pass one argument, a callback function to let us know what happened when the .save() method was called. The first branch of the if statement lets us know what happens if there was an error saving the new BlogPost to the database. The second is the success branch. We have to pass two arguments to this callback. The first is ‘err’, an error object in the case that something goes wrong. The second is ‘blogPost’ which is an object that will hold the saved blogPost.</p><p>If <em>.save()</em> fails, the callback function is going to return an HTTP status code of ‘422’. This is code lets us know that we have an “ <a href="https://httpstatuses.com/422">Unprocessable Entity</a>”. This code let’s us know that “The request was well-formed but was unable to be followed due to semantic errors”. We attach that to the response object with res.status(422). Then we chain on some JSON for a more detailed, human-friendly response from the server. We are going to send an object with two properties: the first is a message (‘msg’) to let ourselves (or another future developer, it’s not all about you) know what when wrong in plain English. The second property (‘error’) has the value ‘err’ which is the error object sent back from our app. When we test our app, we will see some error objects from Mongoose.</p><p>If .save() is successful we respond with a success status of ‘200’ and some JSON. Similar setup except instead of sending an error (because there was none), we return the blogPost object that was just stored in the database.</p><h4>router.js</h4><p>Our app now knows what to do when it receives a new blogPost (controller), and it knows what it should look like (model). But it doesn’t yet know <em>when</em> to do it. For this we need to define some routes. Here’s the code for router.js.</p><pre>// router.js<br>const express = require(&#39;express&#39;);</pre><pre>const BlogController = require(&#39;./controllers/blogpost.controller&#39;);</pre><pre>module.exports = app =&gt; {<br>  // route groups<br>  const apiRoutes = express.Router();<br>  const blogPostRoutes = express.Router();</pre><pre>  // middleware for apiRoutes<br>  apiRoutes.use(&#39;/blogPosts&#39;, blogPostRoutes);</pre><pre>  //// Blog Post Routes //////////////<br>  // POST a new blog post<br>  blogPostRoutes.post(&#39;/&#39;, BlogController.publishPost);</pre><pre>  // url for all API routes<br>  app.use(&#39;/api&#39;, apiRoutes);<br>};</pre><p>First we need to import express. We need to do this so that we can call the .Router() method to create two new router objects in just a little bit. Next we import the controller module we just created.</p><p>The rest of the code is one function. We pass <em>app </em>as an argument so that we can attach our routes at the end. We also export this function to be used in <em>server.js</em>.</p><p>We set up two route groups. One will be our all encompassing <em>apiRoutes</em>. For this tutorial we will only have blog posts, so this isn’t really a necessary step. But consider a future where you want to save details of people that visit your site, or their comments. Those would fall under your API, but wouldn’t be blog posts. Which is our next group, <em>blogPostRoutes</em>.</p><p>Now we need to set up the middeware for our apiRoutes. We simply need to tell it what do do when a route is encountered. If you peek at the last line of code you’ll see we’re telling the app itself what do to when a request comes on ‘/api’. It should use apiRoutes middleware. So whenever a request comes on ‘/api/blogPosts’, our app will use whatever functions we attach to <em>blogPostRoutes</em>.</p><p>We’re only going to define behavior for one HTTP verb for blogPostRoutes, POST at this time. So whenever a HTTP POST request comes on /api/blogposts/, our app is going to use the function <em>BlogController.publishPost()</em>. We just wrote that function in the controller in the previous section.</p><h4>Back to server.js</h4><p>I’m going to go ahead a share the entire <em>server.js</em> instead of just the lines you need to add. I recommend you go line by line and add or modify each line as you encounter it as opposed to just copy and pasting. If you want to copy and paste, just clone the repo. <em>Note: Node is not going to like it when you save this file because MongoDB is not running. We’ll start MongoDB in the next step.</em></p><pre>// server.js<br>const bodyParser = require(&#39;body-parser&#39;);<br>const express = require(&#39;express&#39;);<br>const mongoose = require(&#39;mongoose&#39;);<br>const config = require(&#39;./app/config&#39;);<br>const router = require(&#39;./app/router&#39;);</pre><pre>const app = express();</pre><pre>app.use(bodyParser.json());</pre><pre>app.set(&#39;port&#39;, config.port);<br>app.listen(app.get(&#39;port&#39;), err=&gt;{<br>  if(err) console.error(err);<br>  console.log(`Server listening on port ${app.get(&#39;port&#39;)}...`);<br>  const db = mongoose.connect(config.db);<br>  mongoose.connection.on(&#39;connected&#39;, () =&gt; {<br>    console.log(`Mongoose connected to ${config.db}`);<br>  });<br>});</pre><pre>router(app);</pre><p>The first additions are the imports for <em>config.js</em> and <em>router.js</em>. Now our app is fully aware of the functions we just wrote and we can use them at will in <em>server.js</em>.</p><p>Next we tell the app to use <em>bodyParser</em>. We need this in order for the app to be able to parse the <em>req.body</em> in the controller function <em>.publishPost()</em>. Why this doesn’t just come with express, I don’t know. I think it used to. We use the <em>.json()</em> method for parsing JSON requests. Our front end isn’t going to be sending data straight from a form (I read somewhere that that’s no longer fashionable). We are going to send it as JSON.</p><p>Now look inside our <em>app.listen()</em> method after the console.log where we announce the server is listening. This is where we actually connect to the database via <em>mongoose.connect()</em>. It handles all the nitty gritty in the background. Then, we call the <em>.on()</em> method to let us know when the database is connected.</p><p>If for some reason your server isn’t running, type ‘nodemon’ in your shell, and you should see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*YU7RM2Z9by1fGnmcPr2eSw.png" /><figcaption>Server running and connected to our database</figcaption></figure><p>This would be a good time to push some code. Press CTRL+C to stop the server and get your prompt back.</p><p>We don’t need to push all of those node modules to our repo. Add a new file to your root directory as such:</p><pre>touch .gitignore</pre><p>Open this newly created file and add this single line.</p><pre>node_modules/</pre><p>This will tell git to ignore this directory and all of its contents. Now, type these commands.</p><pre>$ git add .<br>$ git commit -m &quot;POST route for blogPosts written but not tested&quot;<br>$ git push -u origin master</pre><h3>Time for a Test</h3><p>We need to get MongoDB up and running. Open up a <strong>separate shell window</strong> and navigate to where your mongod.exe is located. Depending on the version of MongoDB you have installed, it may be in a differently location. In my case it was:</p><pre>$ cd &quot;c:\program files\mongodb\server\3.6\bin&quot;</pre><p>Then type:</p><pre>$ mongod</pre><p>You now have MongoDB up and running. You can minimize this new shell window.</p><p>Now that we have one fully formed route, we need to test it to make sure it works as expected. First we need to modify our <em>server.js</em> so that we use our <em>test_port </em>and <em>test_db</em>.</p><pre>// server.js<br>if(process.env.NODE_ENV === &quot;test&quot;) {<br>  app.set(&#39;port&#39;, config.test_port);<br>  app.listen(app.get(&#39;port&#39;), err =&gt; {<br>    if(err) console.error(err);<br>    console.log(`Server listening on port$ {app.get(&#39;port&#39;)}...`);<br>    const db = mongoose.connect(config.test_db);<br>  });<br>} else {<br>  app.set(&#39;port&#39;, config.port);<br>  app.listen(app.get(&#39;port&#39;), err =&gt; {<br>    if(err) console.error(err);<br>    console.log(`Server listening on port ${app.get(&#39;port&#39;)}...`);<br>    const db = mongoose.connect(config.db);<br>    mongoose.connection.on(&#39;connected&#39;, () =&gt; {<br>      console.log(`Mongoose connected to ${config.db}`);<br>    });<br>  });<br>}</pre><p>We set up a simple if statement to check if we are running tests or not. If we are running tests, we want to use our test variables. If we are in ‘live’ (or ‘production’) mode, we want to use the regular port and db variables. We will set that environment variable to test in the next step.</p><h4>blogpost.test.js</h4><p>Let’s break this into two parts for digestibility: the set up and the test itself.</p><pre>// blogpost.test.js<br>process.env.NODE_ENV = &#39;test&#39;;</pre><pre>const BlogPost = require(&#39;../app/models/blogpost.model&#39;);<br>const server = require(&#39;../server&#39;);</pre><pre>const chai = require(&#39;chai&#39;);<br>const expect = chai.expect;<br>const chaiHttp = require(&#39;chai-http&#39;);<br>chai.use(chaiHttp);</pre><pre>const blogURL = &#39;/api/blogposts&#39;;</pre><p>As I just promised, we set the Node environment variable to<em> ‘test’</em>.</p><p>Next we required a few things. First we import the BlogPost model so that we can use the methods from mongoose.model. Namely .remove(). Then we import our old friend server.js. <strong>Remind me</strong> to go back there and add a small line of code so that this line works.</p><p>The next four lines are our for our testing framework. And the last line is the URL for our API. The one we set up in router.js. Here is the test itself.</p><pre>// blogpost.test.js<br>describe(&#39;Blog Posts&#39;, () =&gt; {<br>  beforeEach(done =&gt; {<br>    BlogPost.remove({}, err =&gt; {<br>      if(err) console.error(err);<br>      done();<br>    });<br>  });<br>  describe(&#39;/POST/ - publish a BlogPost&#39;, () =&gt; {<br>    it(&#39;it should POST a new BlogPost&#39;, done =&gt; {<br>      const NewBlogPost = {<br>        url: &#39;my-first-blog-post&#39;,<br>        title: &#39;My First Blog Post&#39;,<br>        body: &#39;This is some text. Lorem ipsum... etc...&#39;,<br>        tags: [&#39;blog&#39;, &#39;nodejs&#39;, &#39;api&#39;]<br>      };<br>      chai.request(server)<br>          .post(blogURL)<br>          .send(NewBlogPost)<br>          .end((err, res) =&gt; {<br>            expect(res).to.have.status(200);<br>            expect(res.body).to.be.an(&#39;object&#39;);<br>            expect(res.body).to.have.property(&#39;msg&#39;)<br>              .eql(&#39;Successfully published blog post.&#39;);<br>            expect(res.body).to.have.property(&#39;blogPost&#39;);<br>            expect(res.body.blogPost).to.have.property(&#39;url&#39;).and.be.an(&#39;string&#39;).eql(NewBlogPost.url);<br>            expect(res.body.blogPost).to.have.property(&#39;title&#39;).and.be.an(&#39;string&#39;).eql(NewBlogPost.title);<br>            expect(res.body.blogPost).to.have.property(&#39;body&#39;).and.be.an(&#39;string&#39;).eql(NewBlogPost.body);<br>            expect(res.body.blogPost).to.have.property(&#39;tags&#39;).and.be.an(&#39;array&#39;).and.have.length(NewBlogPost.tags.length).eql(NewBlogPost.tags);<br>            expect(res.body.blogPost).to.have.property(&#39;date&#39;);<br>            expect(res.body.blogPost).to.have.property(&#39;_id&#39;);          done();<br>          });<br>    });<br>  });<br>});</pre><p>First we <em>describe </em>what this block of testing does. It’s a way of documenting the tests for your future self and others unlucky enough to maintain your code. All tests related to Blog Posts will fall inside that first arrow function’s brackets.</p><p>beforeEach() is executed before each test in this block of code. Not to be confused with before() which only executes once before the entire block. So before each test we want to remove all blog posts from the database. Now you see why we had to establish a test port and db. It’d be a shame if we had published a few dozen posts then decided to test some new functionality and wiped our production database. The <em>BlogPost.remove()</em> is a mongoose method.</p><p>Next is a nested <em>describe </em>block. <strong>This is the test itself</strong>. The <em>it</em> let’s us know we are actually starting a test.</p><p>We need some data to send to our API, so we create a new object called ‘<em>NewBlogPost</em>’ with some sample data that represents a typical blog post.</p><p>Now we actually perform an HTTP request. We have to use our <em>server.js</em> module because that is our app. Next we tell Mocha to perform a POST request. Then we tell it what to <em>send</em>, in this case the <em>‘NewBlogPost’</em> object we just created.</p><p>Now we <em>.end()</em> our test by testing the response body from our API. So, what do we expect the response to be. I’ll log the response body so you can see for yourself what it looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*AwZlBM35xhXipUtEjqPfOg.png" /></figure><p>This response body is what we will run our <em>expect()</em> tests on. First we test the response itself (not the body) to make sure we got the desired HTTP response code of 200. Then we make sure the <em>res.body</em> is an object, that that object has the property ‘msg’, and that that message is what we specified in blogpost.controller.js.</p><p>Next we check for the ‘blogPost’ property. The next four <em>expects()</em> are easy to predict. We are testing if our res.body has the four properties we sent in the request. We are testing their types and if they are equal to what we set above. We are also testing the length of the ‘tags’ array.</p><p>The next two properties for which we are checking their existence were automatically generated by our app. The ‘date’ property we set as a default in our model.<em> ‘_id’</em> is automatically set by MongoDB itself.</p><p>Finally, we are <em>done()</em> with our test.</p><p>One more thing we need to do to actually run our test. We need our app to know what to do when we run tests. Go to <em>package.json</em> and locate the scripts property. The value should be an object with one property, “test”. Remove the value of the “test” property and replace with the following value</p><pre>// package.json</pre><pre>// replace this<br><em>“test”: “echo \”Error: no test specified\” &amp;&amp; exit 1&quot;</em></pre><pre>// with this<br>&quot;test&quot;: “mocha --timeout 9999 --exit”</pre><p>Mocha is our testing framework. We set the test to timeout at 9999 milliseconds (almost 10 seconds). And lastly we tell it to exit our app, or stop listening on any ports, once it has completed all tests.</p><p>We should be ready. Let’s try it out. Stop your server if it’s running and type.</p><pre>$ npm test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*CVVqe4LRhvVd-mfCpBXHpQ.png" /><figcaption>Our test failed.</figcaption></figure><p>What went wrong? You see that <em>TypeError: app.address is not a function</em>? Remember I told you to remind me to add a line of code to server.js? Well, you forgot. Let’s go back to server.js and add this line to the <strong>very bottom</strong> of the file.</p><pre>// needed for testing porpoises only<br>module.exports = app;</pre><p>We were unable to import <em>server.js</em> to our test because we never exported it. In production we won’t need to do this. Now go back and run the test again. Here’s a screenshot of what you should be seeing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*tfHLFdXX8ZiPqU7soj183A.png" /><figcaption>Hooray! You’re an app-tester.</figcaption></figure><h4>We need to test our failure branch</h4><p>Remember in our model we required some of our fields. Let’s test our app to ensure those validations are working. Let’s see what happens if we try to publish a blog post without a body.</p><p>Go back to blogpost.test.js and immediately after the <em>it </em>block and right before the closing curly bracket of the ‘/POST/’ describe blog enter this code.</p><pre>it(&#39;it should not POST a new BlogPost without a body&#39;, done =&gt; {<br>      const NewBlogPost = {<br>        url: &#39;my-first-blog-post&#39;,<br>        title: &#39;My First Blog Post&#39;,<br>        tags: [&#39;blog&#39;, &#39;nodejs&#39;, &#39;api&#39;]<br>      };<br>      chai.request(server)<br>          .post(blogURL)<br>          .send(NewBlogPost)<br>          .end((err, res) =&gt; {<br>            expect(res).to.have.status(422);<br>            expect(res.body).to.be.an(&#39;object&#39;);<br>            expect(res.body).to.have.property(&#39;msg&#39;)<br>              .eql(&#39;Server encountered an error publishing blog post.&#39;);<br>            expect(res.body).to.have.property(&#39;error&#39;).and.be.an(&#39;object&#39;);<br>            expect(res.body.error).to.have.property(&#39;errors&#39;)<br>              .and.be.an(&#39;object&#39;);<br>            expect(res.body.error.errors).to.have.property(&#39;body&#39;)<br>              .and.be.an(&#39;object&#39;);<br>            expect(res.body.error.errors.body).to.have.property(&#39;kind&#39;)<br>              .eql(&#39;required&#39;);<br>          done();<br>          });<br>    });</pre><p>You’ll notice this is very similar to the previous ‘success’ test. The first difference is the malformed ‘NewBlogPost’ object. It doesn’t have a body property. That’s the point of this test. Run the test and you should see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*sEDzNC9fis-8t1yqHcVzKQ.png" /><figcaption>Have you ever succeeded at failing? You have now.</figcaption></figure><p>We test for the status code (500) and for the error ‘msg’ we set in blogpost.controller.js. Next we test for the ‘error’ property we set which contains the ‘errors’ property from Mongoose. This <em>errors </em>object is expected to tell us which property we forgot to include. This property is also an object which tells us which ‘<em>kind</em>’ of error we triggered. In this case it is the ‘<em>required</em>’ error, because the <em>‘body’ </em>property is a required member of a <em>BlogPost</em>.</p><p>If we didn’t require a body in our model, this failure test would have failed. And, no, double negatives don’t equal a positive in this instance. Try it for yourself. Go into your<em> blogpost.model.js</em> and remove the “required: true” from the the “body” field. (Don’t forget to remove the comma after String or you’re going to have a bad time.) Run the test again. You should have 1 passing and 1 failing. Our app will send a 200 status code because it successfully added this body-less blog post to the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*Z2zbHeQKhEjJLDI-JqRONA.png" /><figcaption>Our failure test failed</figcaption></figure><p>Don’t forget to go back and re-add the <em>required: true</em> (and the comma) to your model before you proceed.</p><h3>Implementing new features</h3><p>Let’s implement a new feature and test it, then we can wrap up this tutorial. <strong>I recommend pushing your code before you move onto this step.</strong> We just made a major change, not to our API itself, but we have two tests now and they work. You can always revert to this version of your code if you can’t get it to work after this. With automated testing, we can test our routes every time we make changes.</p><p>I don’t like that we have to create the URL ourselves. I’d rather just send the title, body, and tags and let the app create the URL for us. Let’s add this feature and test it. Open up blogpost.test.js and make these changes. First, remove the ‘url’ property and value from the NewBlogPost object. I just commented it out so you could see exactly what to remove.</p><pre>// blogpost.test.js<br>const NewBlogPost = {<br>  // url: &#39;my-first-blog-post&#39;, // you can remove this line<br>  title: &#39;My First Blog Post&#39;,<br>  body: &#39;This is some text. Lorem ipsum... etc...&#39;,<br> tags: [&#39;blog&#39;, &#39;nodejs&#39;, &#39;api&#39;]<br>};</pre><p>Directly underneath the <em>NewBlogPost </em>object, we need to add a little functionality to turn our title into a URL-friendly format.</p><pre>// blogpost.test.js<br>const theURL = NewBlogPost.title.toLowerCase().split(&#39; &#39;).join(&#39;-&#39;);</pre><p>This is some simple string manipulation that will take the title stored in our NewBlogPost, convert all alphabetic characters to lowercase, split all of the words (where ever there is a space character) into an array, then join all of those words back together with a dash between them.</p><p>Now we need to alter the test itself. On the line where we test the URL we need to change the string we are comparing the response against from ‘NewBlogPost.url’ (since that no long exists) to ‘theUrl’ (the variable we just defined.)</p><pre>// blogpost.test.js</pre><pre>// change this<br>expect(res.body.blogPost).to.have.property(&#39;url&#39;)<br>  .and.be.an(&#39;string&#39;).eql(NewBlogPost.url);</pre><pre>// to this <br>expect(res.body.blogPost).to.have.property(&#39;url&#39;)<br>  .and.be.an(&#39;string&#39;).eql(theURL);</pre><p><em>Note: Go ahead and remove the </em>‘url’ <em>property from NewBlogPost in the second test as well as we are no longer going to be sending a url with our HTTP requests. You don’t </em>have<em> to, but if you don’t, the failure test won’t be 100% accurate. You’d be testing if someone, somehow sent a request with a url field in it, which will never happen.</em></p><p>Open up <em>blogpost.controller.js</em> and enter these two lines at the very beginning of the <em>publishPost()</em> method.</p><pre>const theURL = req.body.title.toLowerCase().split(&#39; &#39;).join(&#39;-&#39;);<br>req.body[&#39;url&#39;] = theURL;</pre><p>This is the exact same string manipulation we performed in our test with the only difference being we are manipulating the <em>req.body.title</em>. The second line is attaching this new string to the ‘<em>url</em>’ property of the <em>req.body</em>.</p><p>Go back and <em>npm test</em> your app. Both tests should pass with flying colors.</p><p><em>Note: we should be doing some input validation and sanitation on the title to ensure the resulting url will be valid because even though only we are ever going to be using this API, we might make mistakes in the future. We should be validating and sanitizing all inputs, but that’s an entirely different conversation.</em></p><p>Finally, push your code.</p><h3>Wrap Up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*I7z44tywzgmDFFtmcDbUlg.png" /><figcaption>Keep it 100</figcaption></figure><p>We now have a Node.js API that we can send POST requests to that will add a blog post to a MongoDB database collection. We also have automated tests that define what will happen when s POST request succeeds or fails.</p><p>Next we will set up and test the other three CRUD operations. We will be able to GET blog posts to display on our blog, UPDATE those posts with new data, and DELETE posts if we no longer want them.</p><p><a href="https://github.com/benmerchant/portapi">Here’s the link to the repo on GitHub.</a></p><p><a href="https://medium.com/@benmerchant/my-javascript-journey-df5a35ad0fac">Learn JavaScript with my Solutions to Check.io Challenges</a></p><p>I’m here to learn myself. So, please leave a comment to let me know about any errors I may have made.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819170280abd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CheckiO Challenge 02: Median]]></title>
            <link>https://medium.com/@benmerchant/checkio-02-median-d41a7aa8b525?source=rss-6a827a815618------2</link>
            <guid isPermaLink="false">https://medium.com/p/d41a7aa8b525</guid>
            <category><![CDATA[checkio]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Ben Merchant]]></dc:creator>
            <pubDate>Sun, 18 Mar 2018 05:12:22 GMT</pubDate>
            <atom:updated>2018-06-11T03:01:56.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*hrYss6uk8stLKeTz43u52w.png" /><figcaption><a href="https://js.checkio.org/mission/median/">Screencap: https://js.checkio.org/mission/median/</a></figcaption></figure><p>In this challenge, you are given an array of integers, and are tasked with returning the median of the list. The <a href="https://en.wikipedia.org/wiki/Median">median</a> is simply the number in the exact middle of a sorted list of numbers. If you have an even number of data points, then the median is the average of the two numbers at the middle of the set.</p><p>As usual, I am initializing variables instead of performing math operations and functions inside of other functions for readability. Ignoring that stipulation and returning those results directly in the if statement, we could cut out over half of the lines of code. <a href="https://github.com/benmerchant/checkio-solutions/blob/master/02-median.js">Here’s the code on GitHub.</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5279d38e5ea579e97d3236f7d44befbf/href">https://medium.com/media/5279d38e5ea579e97d3236f7d44befbf/href</a></iframe><h3>Sordid Sort</h3><blockquote>sordid <em>adj.-</em> involving ignoble actions and motives; arousing moral distaste and contempt.</blockquote><p>Since, median is the middle value of a <em>sorted</em> list, we obviously must first sort the list. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">JavaScript’s own docs</a> report that this method is not “necessarily stable”. This method sorts elements in an array based on their Unicode values. If it encounters numbers, it will convert them to strings before comparing them for conversion.This is truly a contemptible action.</p><p>For example, if you are comparing 5 and 300, this method would sort 300 before 5. This is because the Unicode number for five is “U+0035” and the Unicode number for 3 is “U+0033”. It doesn’t need to check the numbers after the three the same way you wouldn’t check any letters after “b” if sorting the word “bat” and comparing it against the word “a”. Once you see a “b” you know that word definitely comes <em>after </em>the word “a”. Whether this method actually does check those two zeroes or stops the comparison at the “3” is not known to this coder.</p><p>Next, I store the length of the array in a variable <em>data_length. </em>As I already mentioned, this was mainly done for readability, which is an important factor when describing your code to other programmers. Anywhere I used the <em>data_length</em> variable, I could have referenced the <em>.length </em>property of the array. More reasons setting up your function this way:</p><ol><li>Every time you reference this property, the function must use a small amount of processing power. For more complex methods, this could be a significant time sink. Better to do it just once.</li><li>It’s better to store properties and methods in variables as opposed to hard coding them. If you need to revisit your code and alter it in the future, you will have to search your entire code base to find every instance of what you need to change. This way, you only have to change it once.</li></ol><h3>Get In the Middle of <em>if</em></h3><p>We need to know if the length of the array is even or not, as the answer to that question will determine how we ascertain the median of a given list of numbers. We use the Remainder (%) operator to accomplish this. This isn’t a true modulo operator as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators">you can read here</a>. The result of a true Modulo operator would return positive or negative based on the sign of the divisor. This remainder operator take the sign of the dividend. (Irrelevant to our discussion, but good to know moving forward.)</p><h4>Get Even</h4><p>First is the even condition. If the list of numbers is even in length ( <em>e</em>x: [1,4,8,9] ), then the median will be an average of the two in the middle ( [4,8] ). To accomplish this, we find out what the index of the two middle numbers are.</p><p>As I’m sure you know, array indexes in JavaScript start at zero. So when we divide <em>data_length </em>by two, we get the second of the two indexes we need. To get the other, we subtract by one. In our example:</p><pre>exampleArr = [1,4,8,9]<br>exampleArr.length is 4<br>Divided by two: 2<br>exampleArr[2] is the value: 8<br>to get the value: 4<br>-&gt; we subtract 1 from the index we got by dividing the length by 2<br>exampleArr[2-1]: 4</pre><p>Once we have these indexes, we find the average of the elements stored at those positions and place that average in the data variable to be returned after the if statement runs its course. I realized a few things:</p><ol><li>I didn’t set the values at the specified positions as variables and then use those variables to find the average; just couldn’t bring myself to write three lines of code when only one was needed.</li><li>Didn’t need to use the <em>var</em> statement for the data variable because we are just re-initializing, not initializing it for the first time. This is held over from when I was initializing <em>median</em> to be returned at the end, then changed back to fit the paradigm of CheckiO’s function template.</li></ol><h4>let my People Go</h4><p>Part of the reason I was wanting to initialize a variable using the <em>var </em>statement was to display its necessity to use the variable outside of the scope of the if statement. The variables we initialized with <em>let </em>can only be used inside the block of code in which they were initialized.</p><p><em>let </em>declares local variables that are only accessible within the scope of the current block of code. This reduces variable name pollution. A variable initialized with <em>var </em>is defined as a global variable, meaning it can be used anywhere.</p><p>Let’s take the <em>data_length </em>variable for example. If our function was modifying the array in such a way that elements were being added or removed, and we used <em>var </em>to define <em>data_length </em>before the operations, then once the function returned, that variable would no longer contain the correct information.</p><pre>var newArray = [1,4,6,9];</pre><pre>function example(data){<br>  var data_length = data.length;<br>  data = data.pop(); // remove the last element from the array<br>  return data;<br>}<br>// call the function on our array<br>newArray = example(newArray);</pre><pre>// reference the length property<br>console.log(data.length); // output: 3<br>// check the data_length variable<br>console.log(data_length); // output: 4</pre><h4>At Odds</h4><p>The odd route is much simpler to imagine. The median is simply whatever value is stored in the element in the exact center of the array. Finding this index take a small amount of effort.</p><p>If we divide the length of an array [1,4,5,6,9] by two, the value returned will not be an integer. The length of this array is 5. Dividing by two is 2.5. Since the middle of this array is index position ‘2’, we employ Math.floor() to round the number down to the nearest integer regardless of the value of the numbers following the decimals.</p><p>When I first did this solution, I used round, which follows correct rounding rules, and rounds up to ‘3’, which I had to subtract 1 from to get the correct index position.</p><p><em>*Note: I just changed the GitHub file and the gist to show the use of floor() instead of round(). The solution on CheckiO still uses round. Both ways are right. One is better.</em></p><p>Now we just need to store the value at the specified index in the array to the <em>data</em> variable, and we are done.</p><h3>Conclusions</h3><p>My biggest takeaway from this challenge was to review my code before pushing it. I had intended to use round(), but was in such a hurry to push and publish that I forgot to change it from my first working prototype.</p><p>I learned that JavaScript doesn’t have a true modulo operator. That in JS it is officially a “remainder” operator and doesn’t function exactly as you’d expect with negative numbers. Apparently they are working on it including it in future versions.</p><p>Finally, I learned about “Temporal Dead Zones” that can raise errors when using the <em>let</em> statement. To point out a few, errors can occur when declaring the same variable with <em>let</em> in the same scope, when trying to reference a variable declared with <em>let</em> before it is declared (including <em>typeof</em>), or when using <em>let</em> in switch statements.</p><p>Hopefully, you learned something as well.</p><p><a href="https://js.checkio.org/mission/median/publications/BenMerch/js-node/middle-of-the-road/">My solution on CheckiO.org</a></p><p><a href="https://medium.com/@benmerchant/my-javascript-journey-df5a35ad0fac">Why I wrote this story</a></p><p><a href="https://medium.com/@benmerchant/checkio-0-need-a-template-for-future-solutions-f002dcd3debb">How my Node template works</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d41a7aa8b525" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>