<?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 Zak Frisch on Medium]]></title>
        <description><![CDATA[Stories by Zak Frisch on Medium]]></description>
        <link>https://medium.com/@zfrisch?source=rss-b77bb94966c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OarZNJw05u-czH7zH8aedQ.jpeg</url>
            <title>Stories by Zak Frisch on Medium</title>
            <link>https://medium.com/@zfrisch?source=rss-b77bb94966c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 00:13:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zfrisch/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[Calling Promises In Order]]></title>
            <link>https://medium.com/@zfrisch/calling-promises-in-order-1e15a2d141e0?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e15a2d141e0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jquery]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 21:09:48 GMT</pubDate>
            <atom:updated>2019-07-30T21:09:48.847Z</atom:updated>
            <content:encoded><![CDATA[<p>A Guide to Serialize JavaScript Promises without a library</p><h4>Introduction</h4><p>One of the most common questions I see crop up in forums, Q and A sites, and on code-centric sites on the StackExchange Network, is <em>“How can I call Promises one by one?”</em></p><p>First off, if you’ve found yourself reading this article, it’s likely that you’ve searched the Internet for a solution. You’ve probably spent hours scouring for an answer to your specific problem and it’s probable you’re rather frustrated.</p><p>I want to let you know — you have a right to be frustrated. Promises are an amazing asset to JavaScript, however, the current methods (such as Promise.all ) lack the simple capacity to perform requests sequentially. Why? Who knows. <strong>It’s an obvious source of pain for a lot of Developers, and, most importantly, you’re not crazy!</strong></p><p>This post isn’t meant to be too deep so I’ll get right into how to resolve this issue with a reusable solution, so that you never have to really think about it again!</p><h3>A Simple Solution</h3><p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator">Symbol.iterator</a> in combination with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of">for await</a> to perform asynchronous execution of your promises. This can be packaged up into a constructor, in the example case it&#39;s called Serial (because we&#39;re going through promises one by one, in order)</p><pre>function Serial( promises = [] ) {<br>  return {<br>    promises,<br>    resolved: [],<br>    addPromise: function( fn ) {<br>      promises.push( fn );<br>    },<br>    resolve: async function( cb = i =&gt; i, err = ( e ) =&gt; console.log( &quot;trace: Serial.resolve &quot; + e ) ) {<br>      try {<br>        for await ( let p of this[ Symbol.iterator ]() ) {}<br>        return this.resolved.map( cb );<br>      }<br>      catch ( e ) {<br>        err( e );<br>      }<br>    },<br>    [ Symbol.iterator ]: async function*() {<br>      this.resolved = [];<br>      for ( let promise of this.promises ) {<br>        let p = await promise().catch( e =&gt; console.log( &quot;trace: Serial[Symbol.iterator] ::&quot; + e ) );<br>        this.resolved.push( p );<br>        yield p;<br>      }<br>    }<br>  }<br>}</pre><h3>What is the above?</h3><ul><li>It’s a constructor called Serial.</li><li>It takes as an argument an array of Functions that return Promises.</li><li>The functions are stored in Serial.promises</li><li>It has an empty array stored in Serial.resolved - this will store the resolved promise requests.</li><li>It has two methods:</li><li>addPromise: Takes a Function that returns a Promise and adds it to Serial.promises</li><li>resolve: Asynchronously calls a custom Symbol.iterator. This iterator goes through every single promise, waits for it to be completed, and adds it to Serial.resolved. Once this is completed, it returns a map function that acts on the populated Serial.resolved array. This allows you to simply call resolve and then provide a callback of what to do with the members in the response. If you return the promise to that function, you can pass a then function to be given the whole array.</li></ul><p>An Example:</p><pre>promises.resolve( ( resolved_request ) =&gt; {</pre><pre>    //do something with each resolved request </pre><pre>    return resolved_request;<br>  } )<br>  .then( ( all_resolved_requests ) =&gt; {</pre><pre>    // do something with all resolved requests </pre><pre>  } );</pre><p>The below example shows how this can be used to great effect, whether you want something to happen on each individual resolution, or wait until everything is completed.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FpMPbJq%3Fheight%3D600%26slug-hash%3DpMPbJq%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fpen%2FpMPbJq&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F237873.pMPbJq.small.83ef98ca-600a-4b84-98f8-50e674847e33.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b19d432ff377ee995bdf936a2bf582d0/href">https://medium.com/media/b19d432ff377ee995bdf936a2bf582d0/href</a></iframe><p>Notice that they will always be <strong>in order</strong>. This is evident by the fact that the first timer is set with the highest ms count. The second Promise <strong>will not</strong> even begin until the first has completed, the third won&#39;t begin before the second finishes, etc.</p><p>That brings me to an important point. Though having your Promises Serialized in order is effective, it’s important to realize that this will delay your responses for your data if they take any one of them takes any amount of time. The beauty of Parallel is that, if all goes well, all requests take a shorter amount of time to complete. Something like Serialization is great for if an application has multiple required requests, and the whole thing will fail if one is not available, or if one item relies on another(pretty common).</p><h3>How does it work?</h3><p>By using an iterator that calls each promise one by one, we can be certain that they <strong>are</strong> received <strong>in order.</strong></p><p>Although many people don’t realize this Symbol.iterator is <em>much</em> more powerful than standard for loops. This is for two big reasons.</p><p>The first reason, and the one that is applicable in this situation, is because it <strong>allows for asynchronous calls</strong> that can affect the state of the applied object.</p><p>The second reason is that it can be used to provide two different types of data from the same object. A.e. You may have an array that you would like to read the contents of:</p><pre>let arr = [1,2,3,4];</pre><p>You can use a for loop or forEach to get the data:</p><pre>arr.forEach(v =&gt; console.log(v)); // 1, 2, 3, 4</pre><p>But if you adjust the iterator:</p><pre>arr[Symbol.iterator] = function* () { yield* this.map(v =&gt; v+1); };</pre><p>You get this:</p><pre>arr.forEach(v =&gt; console.log(v)); // 1, 2, 3, 4 for(let v of arr) console.log(v); // 2, 3, 4, 5</pre><p>This is useful for many different reasons, including timestamping requests/mapping references, etc. If you’d like to know more please take a look at the ECMAScript Documentation: <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements">For in and For Of Statements</a></p><h3>Use:</h3><p>It can be used by calling the constructor with an Array of functions that return Promises. You can also add Function Promises to the Object by using</p><pre>new Serial() .addPromise(() =&gt; fetch(url))</pre><p>It doesn’t run the Function Promises until you use the .resolve method.</p><p>This means that you can add promises ad-hoc if you’d like before you do anything with the asynchronous calls. A.e. These two are the same:</p><p>With addPromise:</p><pre>let promises = new Serial( [ <br>    () =&gt; fetch( url ), <br>    () =&gt; fetch( url2 ), <br>    () =&gt; fetch( url3 ) <br>]);</pre><pre>promises.addPromise( () =&gt; fetch( url4 ) );</pre><pre>promises.resolve().then( ( responses ) =&gt; responses )</pre><p>Without addPromise :</p><pre>let promises = new Serial([<br>    () =&gt; fetch(url), <br>    () =&gt; fetch(url2), <br>    () =&gt; fetch(url3), <br>    () =&gt; fetch(url4)<br>])<br>   .resolve()<br>   .then((responses) =&gt; responses)</pre><h3>Conclusion</h3><p>I certainly hope the above Serial constructor and explanation is as useful to you as it has been for me! I ended up creating it haphazardly while building a transpiler in JavaScript, but I never imagined I would see so many questions on how to utilize ordered Promises, and with that in mind, I simply wanted to write this article to put a solution out into the wild!</p><p>Please check out the following resources if you need more information on some of the topics that were touched on!</p><p><strong>Happy Coding!</strong></p><p><strong>MDN:</strong></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of">for await...of - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator">Symbol.iterator</a></li></ul><h4><strong>Serial in Practice:</strong></h4><ul><li><a href="https://stackoverflow.com/a/57262825/3700849">How do I execute four async functions in order?</a></li><li><a href="https://stackoverflow.com/questions/57046890/using-promise-in-loop-results-in-promise-failure/57047524#57047524">Using promise in loop results in Promise failure</a></li></ul><p><em>Originally published at </em><a href="https://gist.github.com/cbdcf3521dcd8824f65b28e77e42737b"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e15a2d141e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda Operators In JavaScript!]]></title>
            <link>https://medium.com/@zfrisch/lambda-operators-in-javascript-d3b39ead2ed7?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3b39ead2ed7</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ecmascript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Tue, 22 Jan 2019 17:02:45 GMT</pubDate>
            <atom:updated>2019-01-22T17:05:01.982Z</atom:updated>
            <content:encoded><![CDATA[<p>A quick sandbox experiment!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhRHwniPmOSQIUgukNqH-Q.jpeg" /></figure><p>Lambda Calculus is a wonderful thing, though I can never tell sometimes if it’s spoken about <em>too much </em>or <em>not enough</em>. In JavaScript though, as of ES6, we have what’s effectively lambda syntax in JavaScript through the fat arrow function syntax. If you’re confused, it’s this:</p><pre> let variable = (param) =&gt; returnable;</pre><p>^ we all know what that is, or at least we all hopefully do. A simple transposition from a “regular” function to it’s equivalent in fat arrow and lambda may help clarify:</p><pre>function fn(returnable) { <br>    return returnable;<br>}</pre><pre>// is analogous to...<br> <br>let fn = (returnable) =&gt; returnable;</pre><pre>// is analogous to...</pre><pre>let fn = λx.x;</pre><p>In the below pen you can add the operator by using alt+l (that’s a lowercase L for lambda) and compile some nifty combinators or what have you! (<strong>note: it’s not quite mobile friendly, though you can view it “as a desktop site” and it should work well enough, but I recommend an actual desktop view!)</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FPXabpY%3Fheight%3D600%26slug-hash%3DPXabpY%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Ffull%2FPXabpY&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F237873.PXabpY.small.31c784a1-6482-4c49-94e0-b60d7e32d92b.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6812db4e25324d9df43174ffee3aa0cd/href">https://medium.com/media/6812db4e25324d9df43174ffee3aa0cd/href</a></iframe><h3>A Few Quick Examples:</h3><p>A simple add function…</p><p>let add = (x) =&gt; (y) =&gt; x+y;</p><p>becomes…</p><pre>let add = λx.λy.x+y;</pre><p>A simple multiply function…</p><p>let mul = (x) =&gt; (y) =&gt; x * y;</p><p>becomes…</p><pre>let mul = λx.λy.x*y</pre><p>For those into functional algorithms(combinators and the like) you can transcribe this rather easily as it’s almost direct from mathematical notation. A simple K combinator (which is a function that takes a function and a parameter, calls the function with the parameter, and then returns the original function) would go from this…</p><pre>let k = (fn) =&gt; (param) =&gt; (fn(param), fn);</pre><p>to this…</p><pre>let k = λx.λy.(x(y),x);</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FPXabpY%3Fheight%3D600%26slug-hash%3DPXabpY%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Ffull%2FPXabpY&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F237873.PXabpY.small.31c784a1-6482-4c49-94e0-b60d7e32d92b.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6812db4e25324d9df43174ffee3aa0cd/href">https://medium.com/media/6812db4e25324d9df43174ffee3aa0cd/href</a></iframe><p><strong>Okay, Okay!</strong></p><p>Admittedly it’s not life-changing, but it has a certain beauty to it, and it makes it much easier to type out some code on mobile(a constant issue if you’re away from the desk/bluetooth keyboard!)</p><p><strong>Note: There are potential bugs!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3b39ead2ed7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IDs and Classes for Beginner Web Devs]]></title>
            <link>https://medium.com/@zfrisch/ids-and-classes-for-beginner-web-devs-c89b963ddb04?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c89b963ddb04</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 21:00:55 GMT</pubDate>
            <atom:updated>2018-11-09T21:00:55.933Z</atom:updated>
            <content:encoded><![CDATA[<p>quick rules for when to use them</p><p>I love people that have decided to learn how to code. I think it’s an amazing thing to aspire to do, as well as incredibly enjoyable, and it will vastly improve anyone’s cognitive abilities when it comes to general problem-solving!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I0YhKkyvPsovl4hx" /><figcaption>“black laptop computer turned on” by <a href="https://unsplash.com/@wezlar11?utm_source=medium&amp;utm_medium=referral">Dean Pugh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When you first start out with Web Development it is likely that the first thing you’re going to learn how to do, at least sensibly, is HTML markup. Then, after you have gotten a handle on the few of the basic tags (<em>divs, paragraphs, anchor tags, etc) </em>you’re likely to jump into JavaScript(<em>or JQuery)</em>to add some functionality to a page.</p><p>Here’s the problem I have — very often in the markup phase people don’t really learn what the point of theid and class attributes <em>are</em>.</p><p>How do I know this? Well, my dear coder in training, I spend umpteen hours on the ground floor of sites like StackOverflow and Quora answering the questions of people who are stuck in an effort to get them past whatever problem they currently have, and most often, these happen to be newer Developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kg7rDpPbItHKXg6I" /><figcaption>“question mark neon signage” by <a href="https://unsplash.com/@emilymorter?utm_source=medium&amp;utm_medium=referral">Emily Morter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A big thing, and I would be lying if I didn’t say it was a bit perturbing to me, is that <strong>far</strong> too many people constantly have issues with their code that fall down entirely to using id and class incorrectly. Truthfully I don’t know where these people are learning from, but clearly someone is not doing their diligence in assuring them a solid education. It’s especially bothersome because these are <strong>cardinal rules</strong> of markup and, frankly, they’re not that difficult.</p><p>If you’re having trouble with these things, I hope these rules will help!</p><p><strong>The 4 Rules for an ID</strong></p><ol><li>IDs <em>must</em> be unique at all times.</li><li>You <em>must</em> <strong>not</strong> alter IDs once they are set.</li><li>There are no exceptions to the above rules.</li><li>If you’re trying to think of an exception, <em>stop it</em>. <br>There are <strong>NO EXCEPTIONS</strong> to the above rules.</li></ol><p><strong>The 3 Rules for a Class</strong></p><ol><li>Classes <em>should</em> be used for multiple related items. a.e. <em>Articles, Gallery Images, Cards, etc.</em></li><li>Classes <em>should </em>be as vague as possible to simplify re-use.</li><li>Classes <em>should </em>be used for singular items when there is a possibility that similar items, or at least items requiring similar styling, will exist elsewhere in the application or in future versions.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c89b963ddb04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS Pipeline Operator |> Playground]]></title>
            <link>https://medium.com/wdstack/js-pipeline-operator-playground-9b81508d5fe3?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b81508d5fe3</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Fri, 19 Oct 2018 19:25:56 GMT</pubDate>
            <atom:updated>2018-10-20T12:51:05.999Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript’s newest proposed operator</p><p><strong>Note: If you just want to go to the playground and see the Pipeline operator in action head to the section titled “Let’s Play!” below.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGNdomdmfJgGWzYxVnraEQ.jpeg" /></figure><h4>Intro</h4><p>In the world of JavaScript it seems like things have picked up exponentially in the last decade, but especially in the last few years. From the groundbreaking new changes in ES6 and beyond, which introduced us to such amazing features as functional Array methods, arrow functions, generator functions, iterables, the spread operator, the rest operator, class declarations, default parameter declarations, destructuring, and changes in the way that variables were declared to allow for block-scoping and constants ( <em>quite a lot of stuff, right? </em>)</p><p>… Basically there has been a tidal wave of change (most of it good — though any Dev worth his salt can find <a href="https://github.com/tc39/ecma262/issues/1331"><em>something</em> to gripe about</a>) and, although the sheer mass of the ES6 Spec makes it the most memorable change in recent years, it’s important to realize that the ECMAScript Specification is under continuous development.</p><h4><strong>Pretext for the Pipeline Operator</strong></h4><p>Before we get into this further it’s important to make the distinction that the Pipeline Operator <strong>is NOT </strong>anywhere close to being included into the ECMAScript Specification ( I’ll be referring to it as <strong>The Spec </strong>).</p><p>The Spec is watched over by a group called <strong>TC39</strong> — and in the process of being the guardians of the structure of the web’s most utilized language, they implemented <strong>Stages</strong> ( <strong>1 </strong>proposal, <strong>2 </strong>draft, <strong>3 </strong>candidate, <strong>4</strong> finished ) in order to maintain general order in the cyber universe. I won’t go into the details of this (though you can find out more from Dr. <a href="https://medium.com/u/7fab51e62203">Axel Rauschmayer</a>’s fantastic article <a href="http://2ality.com/2015/11/tc39-process.html">Here</a>) — but the Pipeline Operator is currently only within the <strong>proposal </strong>stage(<strong>Stage 1</strong>) which is basically to say that someone said “Hey, this would be a good idea!”, took ownership, wrote up a document, and submitted the proposal to TC39.</p><p><a href="https://github.com/tc39/proposal-pipeline-operator">GitHub - tc39/proposal-pipeline-operator: A proposal for adding a useful pipe operator to JavaScript.</a></p><h4><strong>Okay, so what does it do?</strong></h4><p>The operator provides a more apparent and succinct way to pass information from function to function.</p><pre>parameter |&gt; fn1 |&gt; fn2;</pre><p>This may sound superfluous considering our abilities in JavaScript to declare callable functions using Fat Arrow syntax:</p><p>let addOne(n) =&gt; n + 1;</p><p>As a matter of fact the reason why I built a playground was so that I could test out the pipeline syntax for myself. If I’m being honest I’m usually pretty stubborn in accepting a lot of the new standards as they come, and I thought that this particular one would be, frankly, unnecessary and a waste of time.</p><p>The magic comes though, when you use functional composition. For instance pretend that I asked you what the following would do in order from first to last:</p><pre>addOne(addTwo(multiplyByThree(5)));</pre><p>Regardless of if you <em>could</em> do it(<em>I have faith in you, lads and ladies</em>)— did you notice that you were forced to read from <strong>right-to-left </strong>?</p><p>The norm though it may be in some cultures, when it comes to programming in JavaScript you’re <strong>writing</strong> from <strong>left-to-right </strong>, you’re thinking from <strong>left-to-right</strong> , and even though the code is interpreted <strong>right-to-left</strong> , why are you forced to read it the <strong>same way</strong> it’s processed? It’s both awkward and silly.</p><p>Now pretend that I asked you the same question ( what would the following do, in order from first to last ) and gave you this code:</p><p>5 |&gt; addOne |&gt; multiplyByTwo |&gt; addTwo;</p><p>Easy, right? I bet it was — though I will admit it’s a given that you might have hesitated if you’ve been programming for quite some time. I did, but it’s only because I had a habit of reading from <strong>right-to-left</strong> when I notice functional composition. Indeed, it was a habit I didn’t even knew I had!</p><p><strong>Two quick notes:</strong></p><ol><li>For further clarity you <em>can</em> separate the lines to make them even more readable.</li></ol><pre>5 <br> |&gt; addOne <br> |&gt; multiplyByTwo <br> |&gt; addTwo;</pre><p>2. You <strong>do </strong>have the option of supplying anonymous functions. The first parameter is the return of the previous function or supplied initial value. The above piped functions can also be written like this:</p><pre>5 <br> |&gt; ((n) =&gt; n + 1)<br> |&gt; ((n) =&gt; n * 2)<br> |&gt; ((n) =&gt; n + 2);</pre><h3>Let’s Play</h3><p>Below is the Pipeline Playground that I coded up to test out the syntax. Keep in mind that any JavaScript code you write should be placed within</p><p>&lt;script type=&quot;text/template&quot;&gt;&lt;/script&gt; in the <strong>HTML</strong> section of the Pen.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FBqrXPL%3Fheight%3D600%26slug-hash%3DBqrXPL%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fpen%2FBqrXPL&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F237873.BqrXPL.small.5303c058-8645-4bf9-94ed-49d061d9b151.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5611f61bf7277f7db298243539dac4f/href">https://medium.com/media/c5611f61bf7277f7db298243539dac4f/href</a></iframe><p>For an explanation of how I coded up an environment to test out features please take a look at my previous article <a href="https://medium.com/wdstack/understanding-javascript-micro-templating-f37a37b3b40e">Understanding JavaScript Micro-Templating</a> (It sounds much more complicated than it is, I guarantee it!)</p><p><strong>Conclusion</strong></p><p>The Pipeline operator is an interesting concept, and definitely one that has had similar operators appearing in other languages for decades. It would be an interesting addition to JavaScript, and I think it does have a lot of merit, especially in the form of clarity for Developers.</p><p>There is one sore spot, and that’s when it comes to multiple arguments being piped into functions:</p><pre>(5, 6) |&gt; addTogether;</pre><p>The above will not work, and I do believe that there needs to be some kind of ability to pipe multiple arguments to a singular function - at least initially, though I suppose in the meantime an array may suffice, a.e. :</p><pre>[1,2]<br>  |&gt; ((a) =&gt; a[0] + a[1])<br>  |&gt; console.log;         // 3</pre><p>In any case, I hope you’ve enjoyed this article, and a brief introduction into the Pipeline Operator!</p><p>Happy Coding!</p><p><strong>Resources For More Information:</strong></p><ul><li><a href="http://2ality.com/">2ality - JavaScript and more</a></li><li><a href="https://www.ecma-international.org/memento/tc39-rf-tg.htm">TC39-Royalty Free TG</a></li><li><a href="https://github.com/tc39/proposal-pipeline-operator">GitHub - tc39/proposal-pipeline-operator: A proposal for adding a useful pipe operator to JavaScript.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b81508d5fe3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wdstack/js-pipeline-operator-playground-9b81508d5fe3">JS Pipeline Operator |&gt; Playground</a> was originally published in <a href="https://medium.com/wdstack">WDstack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Short-Hand Function Technique]]></title>
            <link>https://medium.com/wdstack/short-hand-function-technique-9c188323f0b3?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c188323f0b3</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 17:20:26 GMT</pubDate>
            <atom:updated>2018-07-02T19:47:00.482Z</atom:updated>
            <content:encoded><![CDATA[<p>A Quick Way to Minify Methods in JavaScript</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YX17JOSlZlhe0PSsQ16hNA.jpeg" /></figure><p>As a programmer I’m often toying with different ways of doing things and quite a few at one time( <em>too many? probably )</em> — but when it comes to programming my mind is constantly brimming with ideas.</p><p>I was experimenting with adding short-hand to the document object based on the camel case naming convention. “<em>Whoa whoa whoa,” </em>you protest, “<em>what’s that mean, man?”</em></p><p>Basically I wanted to turn document.querySelector and document.addEventListener into document.qS and document.aEL respectively. <strong>why? </strong>I’m profoundly lazy and curious. It’s true that this isn’t a real big achievement. It can be done as simply as:</p><pre>document.qS = document.querySelector;<br>document.aEL = document.addEventListener;</pre><p>but I wanted to adjust the object in such a way that all camel cased methods became adapted to a short-hand method. Frankly, I was just tired of writing out these long chained methods and wondered if I could make it easier. Not for production, of course, but to sate my own silly desire and to use to mock-up some play code occasionally.</p><p>The following is a demo of what I came up with and an explanation:</p><pre>let b, d, e; <br>for(let k in(d=document)) d[k[0]+k.split(&quot;&quot;).filter(_=&gt;_&lt;{}).join(&quot;&quot;)] = d[k];</pre><pre>e=_=&gt;d.qS(_);<br>b=_=&gt;d.aEL.bind(_); </pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FZRmjeJ%3Fheight%3D600%26slug-hash%3DZRmjeJ%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fpen%2FZRmjeJ&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a1b9541ae96e01a90a59bb42d755d43/href">https://medium.com/media/4a1b9541ae96e01a90a59bb42d755d43/href</a></iframe><p>What’s happening here?</p><ul><li>I’m declaring d as document</li><li>Iterating through each of the keys in document</li><li>Determining the camel case letters of a key (k[0] is the first letter which is lowercase and then I use the filter method on the rest of the key to find any uppercase letters)</li><li>We then apply the first lowercase letter and any uppercase letters found as a new method on document that references the original method - ergo document.querySelector becomes document.qS</li></ul><p><strong>Point of Note: </strong>The above uses a trick of comparing a character to an object to determine its case. If <strong>true</strong> the case is upper, and if <strong>false </strong>the case is lower. Examples:</p><pre>&quot;c&quot;&lt;{}; //false<br>&quot;C&quot;&lt;{}; //true</pre><pre>&quot;E&quot;&lt;{}; //true<br>&quot;e&quot;&lt;{}; //false</pre><p>What’s happening here may seem odd so I’ll explain it:</p><ul><li>an object is converted to a string when it is compared.</li><li>{} in the above example is turned into &quot;[object Object]”</li><li>In ASCII/UTF-16 uppercase A-Zhave character code values from <strong>65–90 </strong>and lowercase a-z have character code values from <strong>97–122.</strong></li><li>[ is character code <strong>91 </strong>which is between both character sets. This means that when &quot;A&quot;&lt;{} it is comparing &quot;A&quot; or character code <strong>65</strong> with &quot;[&quot; or character code <strong>91</strong>.</li><li>Since 65 is less than 91 &quot;c&quot;&lt;{} is <strong>true</strong> which we can interpret as the character being uppercase.</li><li>If it were &quot;a&quot;&lt;{} we would be comparing character code <strong>97</strong>(a) with character code <strong>91</strong>([)</li><li>Since <strong>97 </strong>is not less than <strong>91 </strong>&quot;a&quot;&lt;{} is <strong>false </strong>which we can interpret as the character being lowercase.</li><li>It’s important to realize that {} <strong>doesn’t have to be an empty object</strong> — it can be any object since all objects convert to &quot;[object Object]&quot; when turned into a string.</li></ul><h4><strong>Short Hand in Custom Objects</strong></h4><p>The shortening of the methods on the document object is certainly interesting but it wasn’t foolproof by any stretch of the imagination. Sure, document.qS and document.aEL came out working, but what if I had two methods that utilized the same camel case characters? The document object wasn’t built with my crazy short-hand nonsense in mind so it was completely unreliable when it came to what methods I would be adjusting.</p><p>but what about my own, custom objects? “<em>Let me try that!</em>”, I shout from my home desk at 3am, haphazardly falling out of my chair and spilling tea all over my Walking Dead pajamas because I’m just <strong>that excited</strong>.</p><h4><strong>Further Code Explanation</strong></h4><p>The following code is nothing special. It is a copy of the above code in a functional format, with an error that will occur if I run into a duplicate of the same key. For instance, if I had addEventListener (aEL) and abstractEventLoop (aEL) on the passed object it would throw an error because I don’t want two keys to have the same short-hand name and overwrite each other. You may think that this is fine as long as the one key you’d like as short-hand comes after the other, but this is impossible to guarantee. Object keys are not returned in any finite order so we can’t rely on that. Anyway, here’s the function ( ObjectCheck )</p><pre>// the short-hand technique<br>function ObjectCheck(myObject) {<br>  let obj = Object.assign(myObject, {});<br>  for (let key in obj) {<br>    if (!(/^([a-z])([A-Z])+$/).test(key)) {<br>      let formatted = key[0] + key.split(&quot;&quot;).filter(_ =&gt; _ &lt; obj).join(&quot;&quot;);<br>      if (formatted in obj) throw Error(&quot;Key already Exists. Object is not short-hand capable&quot;);<br>      else obj[formatted] = obj[key];<br>    }<br>  }<br>  return obj;<br>}</pre><p>Just to explain once more because by golly(<em>who says </em><strong><em>by golly</em></strong><em> anymore?</em>) that doesn’t look the easiest to comprehend. I aim my blog towards anyone tired of jargon and gibberish after all. *cracks knuckles* OKAY, so:</p><pre>function ObjectCheck(myObject) {</pre><pre>}</pre><p>we receive an object when this function is called. Since we’re a big fan of functional programming (<a href="https://medium.com/@zfrisch/understanding-functional-programming-in-javascript-f3477cde7432">Understanding Functional Programming — Zak Frisch</a>) we know that we don’t want to change the object we passed in, what we want to do is create a copy and adjust the copy. To do this we use Object.assign (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign">MDN</a>) which will allow us to duplicate the object. Object.assign will return a copy but it always takes <em>at least </em>two parameters. Our second parameter will be an empty object.</p><pre>function ObjectCheck(myObject) {<br>//duplicate the passed in object(myObject) in obj<br>let obj = Object.assign(myObject, {}); <br>}</pre><p>As in the above code we then need to iterate over the objects keys.</p><pre>for (let key in obj) {<br>    if (!(/^([a-z])([A-Z])+$/).test(key)) {<br>      let formatted = key[0] + <br>      key.split(&quot;&quot;)<br>      .filter(_ =&gt; _ &lt; obj)<br>      .join(&quot;&quot;);<br>      <br>if (formatted in obj) throw Error(&quot;Key already Exists. Object is not short-hand capable&quot;);<br>      else obj[formatted] = obj[key];<br>    }<br>  }<br>  return obj;</pre><p>We use the for...in loop to iterate. There is a Regular Expression that is used to test if a function is camel case before we try adding a shorthand key. We do this because otherwise if we have a method like append it would simply be short-handed to a and we <strong>don’t</strong> want that.</p><p>Afterwards we ask if the camel case key which is stored in the formatted variable (aEL in the case of addEventListener ) is already within obj — remember, we want to prevent any overwriting of keys, so we throw an error that says as much. If formatted is not within obj we assign the original function to our short-hand function. A.e. document[&quot;aEL&quot;] = document[&quot;addEventListener&quot;]</p><p>Still confusing? That’s <strong>fine! </strong>Let’s try it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvKTtoxMX0Ha1Shz_i2HNw.jpeg" /></figure><h4>Custom Object Example</h4><p>In the above section we created our ObjectCheck function which will check if our object is short-hand capable and convert it! We still need an object to convert. Let’s create a simple one:</p><pre>{<br>sayHello() {<br>    document.body.innerText += &quot; hello!&quot;<br>    return this;<br>  },<br>  sayGoodbye() {<br>    document.body.innerText += &quot; goodbye!&quot;;<br>    return this;<br>  }<br>}</pre><p>The above code is an object with two methods: sayHello and sayGoodbye — they will add hello to the screen or goodbye to the screen respectively.</p><p>Simple right? If you don’t understand return this — what that is doing is, instead of stopping after adding the text to the screen, it returns the object back after using its method. This allows you to call other methods immediately ( what we call <strong>chaining </strong>methods)and it looks like this: obj.sayHello().sayGoodbye().sayGoodbye().sayHello(); which we can use instead of writing:</p><pre>obj.sayHello();<br>obj.sayGoodbye();<br>obj.sayGoodbye();<br>obj.sayHello();</pre><p>It’s a pretty common technique used by most JavaScript libraries — most notably JQuery. <em>Anyway…</em></p><p>We’re going to pass this object to our short-hand converter and use it. What we should see from the returned object is that we have the ability to use sayHello as sH and sayGoodbye as sG — let’s try it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FaKMwQy%3Fheight%3D600%26slug-hash%3DaKMwQy%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fpen%2FaKMwQy&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/21953e7b0ff7ff1907510418b1e7ae40/href">https://medium.com/media/21953e7b0ff7ff1907510418b1e7ae40/href</a></iframe><p>As you can see our ObjectCheck function worked beautifully.</p><pre>let myobj = ObjectCheck({<br>  sayHello() {<br>    document.body.innerText += &quot; hello!&quot;<br>    return this;<br>  },<br>  sayGoodbye() {<br>    document.body.innerText += &quot; goodbye!&quot;;<br>    return this;<br>  }<br>});</pre><pre>myobj.sH().sG().sH().sG();</pre><p>We can now use this to short-hand any objects that we want to use and get sick of writing out full method names for. Now, depending on your disposition, you may say “<em>Wait a minute, Zak. That adds twice as many keys on the same object!</em>” or “<em>Zak, that’s great, I can now switch back and forth between the two keys if I’m feeling lazy or want to be clear!”</em> — really it’s all down to how you view it.</p><p>One last thing in the interest of clarity. It’s important to realize that because our short-hand functions are direct references to the full named functions, any change to the full named functions will affect how the short-hand function evaluates. The short-hand function is not a copy, it is a reference. This works out fine for me, but it may surprise some people if you’re not aware of it. Secondly, this leads to a trick. If you ever find yourself coding in short-hand and forgetting what it is that your short-hand function references you can simply use obj.fn.name to retrieve the full length name.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FeKXggJ%3Fheight%3D600%26slug-hash%3DeKXggJ%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fpen%2FeKXggJ%3Feditors%3D1010&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/192f1a8c70aef44da03540f5abeef851/href">https://medium.com/media/192f1a8c70aef44da03540f5abeef851/href</a></iframe><h4>Conclusion</h4><p>I enjoyed implementing this technique and it helped me kick off dust on a few of my stagnant brain-cells. I’ve decided to use it in several small projects in solidarity for that part of me that always loves to write shorter code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8rVS2cXWqx1WMb--aDYEg.jpeg" /></figure><p>Typically in my conclusion sections I have some follow-up information, and more in-depth explanation of concepts, but this time I think I’ll avoid all that as the bulk of information is provided in the article itself. I just wanted to share an interesting idea that I had and the thought process that allowed me to flesh it out! Maybe someone will find it useful or expand on the idea!</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c188323f0b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wdstack/short-hand-function-technique-9c188323f0b3">The Short-Hand Function Technique</a> was originally published in <a href="https://medium.com/wdstack">WDstack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Functions in JavaScript]]></title>
            <link>https://medium.com/@zfrisch/writing-functions-in-javascript-de839053e9a8?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/de839053e9a8</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Fri, 02 Mar 2018 17:55:07 GMT</pubDate>
            <atom:updated>2018-03-03T21:06:53.937Z</atom:updated>
            <content:encoded><![CDATA[<p>A Basic Guide for New Developers</p><p>Hello there! So you want to learn about JavaScript functions! Maybe you’ve dabbled in the language a bit — maybe you’ve started out an hour ago, who knows? Who cares? It’s irrelevant! Let’s get learning!</p><p>The two topics discussed in this article are the following:</p><ul><li>What is a Function and what is it for?</li><li>How do I create a Function?</li></ul><p>If none of the above sounds interesting, sorry about that! Best of luck in your search, otherwise, let’s jump right in!</p><h4><strong>What is a Function?</strong></h4><p>A function is a list of steps to be completed in JavaScript that can be used over and over.</p><p>This can be thought of as a Grocery List. When you go to the store a Grocery List is a pre-made list that tells you exactly what to put into your cart. If your needs don’t change over time(a.e. you don’t develop a taste for twinkies) you won’t need to update the list at all and can use the same list over and over each time you have to go shopping. Since you use this same list you don’t need to record the information again for subsequent visits. This saves you time and makes you more efficient. This is the point of functions. To easily clear away repetitive tasks.</p><p>The below JavaScript declares three variables.</p><ul><li><strong>a —</strong> <em>which is set to</em><strong><em> 1</em></strong></li><li><strong>b — </strong><em>which is set to</em><strong><em> 3</em></strong></li><li><strong>sum — </strong><em>which is set to</em><strong><em> </em>a <em>+ </em>b</strong></li></ul><pre>var a = 1;<br>var b = 3;<br>var sum = a + b; </pre><p>If we were to print out <strong>sum</strong> we would get <strong>4</strong>. What if we wanted to complete this operation again, maybe with another variable?</p><pre>var a = 1;<br>var b = 3;<br>var sum = a + b; // 4</pre><pre>var c = 2;<br>var sum2 = b + c; // 5</pre><p>The above code will work, but it seems a bit repetitive. We don’t want to have to keep assigning new variables <em>every single time</em> we want to add two numbers together right?</p><p>This is exactly what functions are for. To outsource the process so that instead of the above, we could simply write:</p><pre>add(1,3); // 4<br>add(2,3); // 5</pre><p>but how do we do that? Well first we need to create a function.</p><h4>How to create a Function</h4><p>Function declarations are a bit simplistic, but they can be confusing to newcomers who are unfamiliar. We’ll go over a few examples to try and stick the point home.</p><p>The layout for a function declaration in JavaScript looks like the below. Keep in mind that the caret symbols denote placeholders. a.e. <strong>&lt;name&gt; </strong>would be replaced by a <strong>name </strong>you would like your function to have.</p><pre><strong>function &lt;name&gt;(&lt;parameters&gt;) {</strong></pre><pre><strong>&lt;function body&gt;</strong></pre><pre><strong>}</strong></pre><p>If this is strange, don’t worry, and don’t sit staring at the above for too long. You may find it easier to understand after a real example creating the add function from the above section.</p><p>To recap, the process we would like to turn into a function is this:</p><pre>var a = 1;<br>var b = 3;<br>var sum = a + b; // 4</pre><p>Following the above template for a function, we can make one named <strong>add</strong></p><pre>function <strong>add</strong>() {</pre><pre>}</pre><p>What we need to do with this function is return the sum of two numbers. These two numbers are passed in by the programmer. This means that the function takes two parameters.</p><p>In our code above they are stored in variables <strong>a</strong> and <strong>b</strong>. In our function declaration we can create variables to retrieve those values once they’re passed into the function.</p><p>That probably sounds confusing, but lets take a look at the below:</p><pre>var a = 1;<br>var b = 2;</pre><pre>function add(x, y) { ... }</pre><pre>add(a, b); // 3</pre><ul><li>We declare <strong>a</strong>, <strong>b</strong>, and the function <strong>add</strong>.</li><li>We then invoke <strong>add </strong>passing in the parameters <strong>a </strong>and <strong>b</strong>.</li></ul><p>Inside the function <strong>add</strong> we receive whatever is passed into the function as variables declared within the parentheses of the function declaration. This means that <strong>a </strong>and <strong>b</strong> are referenced inside the function <strong>add</strong> as <strong>x </strong>and <strong>y.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*KsFbDnk-bwulTMGvV_u_6Q.png" /></figure><p>A few more examples of this</p><pre>function add(<strong>x, y</strong>) {<br>return x + y;<br>}</pre><pre>add(1, 2); //x is 1, y is 2</pre><pre>var a = 5;<br>var b = 10;</pre><pre>add(a, b); //x is 5, y is 10</pre><pre>var apple = 0;<br>var windows = 33;<br>add(apple, windows); //x is 0, y is 33</pre><h4>Final Example</h4><p>Lets create a function that adds text to the screen. The following is our plan for a function</p><ul><li>we want a function called “writeToScreen”</li><li>the function will take a string as input</li><li>the function will add text to the screen</li></ul><pre>function writeToScreen(text) {<br>  document.body.innerHTML += text;<br>}</pre><pre>writeToScreen(&quot;Hello!&quot;);</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FoEOvgV%3Fheight%3D600%26slug-hash%3DoEOvgV%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fpen%2FoEOvgV&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/55c10b963e439051d1e2edc34393f732/href">https://medium.com/media/55c10b963e439051d1e2edc34393f732/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de839053e9a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fail your Exams? No Problem!]]></title>
            <link>https://medium.com/@zfrisch/fail-your-exams-no-problem-4d57f5c2ce0b?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d57f5c2ce0b</guid>
            <category><![CDATA[funny]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[exam]]></category>
            <category><![CDATA[college]]></category>
            <category><![CDATA[christmas]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Fri, 22 Dec 2017 17:39:58 GMT</pubDate>
            <atom:updated>2017-12-22T17:43:34.560Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to Forge a Grade and Avoid Embarrassment</h4><p>A lot of you college students probably just failed your exams much to the chagrin of your Family who help out with your weekly beer expenses! What’s worse is they want to see your Grades so they can passive-aggressively insult you in front of all your relatives over a spiteful dinner, <em>oh no</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*SWkmWyXSQKwa3gvq9rzZsA.jpeg" /><figcaption>“Let’s toast to Family! Not you, loser!”</figcaption></figure><p>Here’s a tip:</p><ul><li>Open Chrome.</li><li>Go to the page that displays your grade online.</li><li>Hit ctrl+shift+j to open the console and type in the following:</li></ul><p>document.designMode = &quot;on&quot;;</p><p>You can now click around and edit the page like a word document, keeping styling/coloring/fonts in-tact, and maybe inconspicuously pad that grade a bit and email it to your mum? I’ll leave that up to your sense of ethics, (which incidentally might be the class you failed?)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J18H3jWjmMY_erMhJ-Fg0A.jpeg" /><figcaption>“NOT AT ALL MY GOOD SIR HA. HA. HA.”</figcaption></figure><p>Merry Christmas!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d57f5c2ce0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Intro: Variable Declarations]]></title>
            <link>https://medium.com/wdstack/javascript-intro-variable-declarations-e795e17186ec?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e795e17186ec</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Thu, 14 Dec 2017 19:56:11 GMT</pubDate>
            <atom:updated>2018-03-08T19:20:09.317Z</atom:updated>
            <content:encoded><![CDATA[<p>How to make variables with let, const, and var</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZnKeOjjctNFcP8zxftB3g.jpeg" /></figure><blockquote>“Hey Again! It’s your boi ZF come down from the high mountains geared up and ready to Sherpa. I’m here to drop some sick brain expanding knowledge. Get ready for an intellectual roller coaster to get that brain swole brutha.”</blockquote><p>…is what I would say if my nickname was Beach Muscles and I only wore backwards flat-brimmed hats and wayfarers(for some reason), but hey, we’re going to learn about <strong>JavaScript Variable Declarations</strong> and their differences today so if you’re just starting out with JavaScript or need a refresher this article will aim to help you out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVXicFhmOOyYASuzkM570w.jpeg" /><figcaption>Ready to Learn!</figcaption></figure><h3>Variables</h3><p>Variables in JavaScript have been traditionally declared using a single keyword. That keyword isvar :</p><pre>var a; //create variable a<br>var b; //create variable b<br>var c; //create variable c</pre><p>It used to be about as simple to create a variable in JavaScript as you could get it. No options meant no guesswork. You want a variable? <em>ka-pow! </em>You got it.</p><pre>var whatever; <br>var whoever;<br>var wherever;</pre><p>The only thing that needed to concern you was the name of the variable and that was a very small hurdle(don’t use spaces/don’t begin with a number/decide on naming conventions <em>probably/</em> etc.)</p><p>So why then, in the last few years, were the keywords let and const added to JavaScript as an alternative to var? What functionality do they provide that var doesn’t offer?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrdUKOySJBc7ebN1vzgsFQ.jpeg" /><figcaption>The very ambiguous sign raises a good question</figcaption></figure><h4><strong>let and </strong><strong>var</strong></h4><p>If you look up “Variable Declarations in JavaScript” you’re likely to come across <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript">A Re-Introduction to JavaScript</a> on the Mozilla Developer Network(MDN).</p><p>This article gives a lot of great information and I’ll link to it in the <strong>Resources </strong>section below as well. Even though it is worthwhile to read, the explanations of variable declaratives may <em>seem</em> too technical for the average person or someone just getting into JavaScript. Examples of this are the following:</p><blockquote><strong>let </strong>allows you to declare block-level variables. The declared variable is available from the <em>block</em> it is enclosed in.</blockquote><p>and</p><blockquote><strong>var</strong> is the most common declarative keyword… This is because it was traditionally the only way to declare a variable in JavaScript. A variable declared with the <strong>var </strong>keyword is available from the <em>function</em> it is declared in.</blockquote><p>Try as you might it is a bit much to wrap your head around. Now, I’m not trashing the author here (<em>because as it would happen, I helped write this article) </em>but there’s a lot of mentioning of <strong>blocks </strong>and <strong>block-level </strong>and things being <strong>available from the function they are declared in</strong> — what does all that mean to the uninitiated?</p><p>To break it down simply let and var are almost identical. In fact they are so closely aligned in function that you are encouraged more often than not to simply use let instead of var .</p><pre>let a; //create variable a<br>let b; //create variable b<br>let c; //create variable c</pre><p>“<em>But what </em><strong><em>is</em></strong><em> the difference?”</em></p><p><strong>In Technical Terms:</strong> Their scopes are different.<br><strong>In Layman’s Terms: </strong>If you use <em>let</em> that variable is only visible between the braces <strong>{ } </strong>of the code it’s used in. If you use <em>var</em> that variable may be visible within <em>and outside</em> of the braces <strong>{ } </strong>it’s used in.</p><p><em>I know, I know</em>, saying “<em>may be visible</em>” is a bit confusing when you’re trying to solidify a concept in your head. It may be visible outside a<em> </em><strong><em>block</em></strong>( code between braces <strong>{ } </strong>) if that <strong>block</strong> is <strong>not </strong>a function.</p><p>This will not allow <em>a</em> to be visible outside of the function call:</p><pre>(function() {<br>var a = &quot;a&quot;;<br>}()); //create anonymous function and invoke it immediately.</pre><pre>console.log(a);<br>// throws error a is <strong>not</strong> declared</pre><p>This code will allow <em>a </em>to be visible outside of a for-loop block:</p><pre>for(var i = 0; i &lt; 1; i++) {<br>  var a = &quot;a&quot;;<br>}<br>console.log(a); // &quot;a&quot;</pre><p>So again, using <em>var</em> means that a variable will be visible outside of a block of code <strong>if that block is not, itself, a function.</strong> Really this example is the gist of the difference. The fact is that 99% of the reason to use <strong>let</strong> lay within for-loops.</p><p>An example of a for-loop using<strong>let</strong>:</p><pre>for (<strong>let</strong> i = 0; i &lt; 5; i++) {<br>  // i is only visible in here<br>  console.log(i); <br>}<br>// 1...2...3...4</pre><pre>console.log(i);<br>// throws error &quot;i is <strong>not</strong> declared&quot;</pre><p>An example of for-loop using <strong>var:</strong></p><pre>for (<strong>var</strong> i = 0; i &lt; 5; i++) { <br>  // i is visible in here<br>  console.log(i); <br>}<br>// 1...2...3...4</pre><pre>// i is visible out here<br>console.log(i);<br>// 5</pre><p>The difference is the availability of the variable outside of the for-loop block. Aside from specifically the above situation let and var function the same, so much so that they are interchangeable in every instance but the one. It’s pretty well considered that in time let will phase out var entirely.</p><h4>const</h4><p><strong>const </strong>allows you to declare variables whose values are never intended to change. Like let , the const variable is available from the <em>block</em>(code between braces <strong>{ }</strong> ) it is declared in.</p><p>One thing to keep in mind, const stands for <strong>constant</strong>. This means that once a variable is set it will persist as that value and you can’t change it.</p><p>An example of constinability to change:</p><pre>const Pi = 3.14; // variable Pi is set <br>Pi = 1; // will throw an error because you cannot change a constant variable.</pre><p>That being the case you can’t declare a constant variable and not define it’s initial value at the same time. You only get to define it the once and if you don’t that variable would have a permanent value of undefined — which would be pretty useless, right? Because of this the Browser will typically throw a Type Error if it detects this being done.</p><p>Example:</p><pre>const a; // a is undefined forever. Throws Error.<br>const b; // b is undefined forever. Throws Error.<br>const c = &quot;cat&quot;; // c is defined as &quot;cat&quot; forever</pre><p>As you can imagine you should only use const for values you are positive will not need to be changed in the future. This is particularly useful for instances where you might be working in tandem with other Developers and you know that certain values must never be altered, accidentally or otherwise.</p><p>But there are <strong>exceptions </strong>when it comes to Objects and Arrays.</p><h4>const and Objects</h4><p>In the above section about const you may have come to the conclusion that anything declared as a <strong>constant</strong> is immutable(<em>immutable simply means that the data cannot, under any circumstances, be changed). </em>I’m here to tell your assumption is <strong>incorrect</strong>. The caveat is declaring const objects and arrays.</p><pre>const obj = {<br>  property: &quot;property&quot;,<br>  property2: &quot;property2&quot;<br>}</pre><p>The above declares an object using const underneath the variable obj.<br>This is all well and good. Certainly we can’t do the following and alter the variable obj:</p><pre>const obj = {<br>  property: &quot;property&quot;,<br>  property2: &quot;property2&quot;<br>}<br>obj = {<br>  blah: &quot;blah blah&quot;,<br>  blah2: &quot;blah blah blah&quot;<br>} // throws error assignment to constant variable</pre><p>However, though we can’t change obj through direct assignment, we <strong>can</strong> alter it through property/method assignment. This means we can assign to all of obj ‘s child properties and methods(and even delete them) by being more specific instead of trying to cram everything into obj at once:</p><pre>const obj = {<br>  property: &quot;property&quot;,<br>  property2: &quot;property2&quot;<br>}<br>delete obj.property; // remove property<br>delete obj.property2; // remove property2</pre><pre>obj.blah = &quot;blah blah&quot;; // add blah<br>obj.blah2 = &quot;blah blah blah&quot; // add blah2</pre><p>This does mean that const doesn’t make a variable immutable/unchangeable, at least not always. If you’re interested(for whatever reason) in total immutability you can always look into using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">freeze</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal">seal</a> object methods. I’ll also put links to some good helper articles and Stack Overflow questions in the <strong>Resources </strong>section.</p><h4>const and Arrays</h4><p>Arrays are also immutable as defined by their type. The Array stored within a variable is a reference to where data can be found, not the data itself.</p><p>This allow for the following Array to be changed after its declaration:</p><pre>const arr = [&quot;hi&quot;, &quot;hola&quot;];<br>arr[0] = &quot;blue&quot;;<br>console.log(arr); // [&quot;blue&quot;, &quot;hola&quot;]</pre><p>I’ll also put links to some good helper articles and Stack Overflow questions in the <strong>Resources </strong>section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJj4hmOES-c0DYj4Kwg89A.jpeg" /></figure><h3>In Conclusion</h3><p>let and const are definitely valuable to the JavaScript community. They offer alternative scoping functionality that allows for less worry in regards to variables being fudged up in unexpected ways. That’s all. In the future, as stated above, var may not be phased out for legacy reasons but I would bet that it will become frowned upon to use outside of simple tests or example work.</p><h3>Resources</h3><ul><li><a href="https://stackoverflow.com/questions/48468819/can-the-value-of-a-variable-declared-using-const-be-changed/48469063#48469063">Can the value of a variable declared using const be changed?</a></li><li><a href="https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable">What&#39;s the difference between using &quot;let&quot; and &quot;var&quot; to declare a variable?</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript">A re-introduction to JavaScript (JS tutorial) - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal">Object.seal()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">Object.freeze() - JavaScript | MDN</a></li><li><a href="https://stackoverflow.com/questions/21402108/difference-between-freeze-and-seal-in-javascript">Difference between freeze and seal in Javascript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e795e17186ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wdstack/javascript-intro-variable-declarations-e795e17186ec">JavaScript Intro: Variable Declarations</a> was originally published in <a href="https://medium.com/wdstack">WDstack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTML Forms Are Kind Of Terrible]]></title>
            <link>https://medium.com/@zfrisch/html-forms-are-kind-of-terrible-1d61ffd9d9ea?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d61ffd9d9ea</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[html5]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Thu, 07 Dec 2017 21:22:49 GMT</pubDate>
            <atom:updated>2017-12-07T21:22:49.977Z</atom:updated>
            <content:encoded><![CDATA[<h4>What’s Wrong and Why</h4><p>It’s no secret that when it comes to Professional Web Development a lot of time will be spent messing with HTML Forms. While the spec has expanded to include <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">Constraint Validation</a> which is a boon to the way that Forms are currently processed when they’re heading towards the Server, I still insist that to any seasoned Developer not jaded into using bloated libraries, Client-Side Dynamic HTML Forms are kind of terrible.</p><p>(my solution for easily saving/loading and retrieving input values can be found here: <a href="https://github.com/zfrisch/Input-Management/blob/master/input_management.js">Input Management “Library”</a> — use and examples are thoroughly explained further down this article)</p><h3><strong>Why?</strong></h3><p>For one thing the markup for them doesn’t exactly make a ton of sense in present time. Sure we have the input tag that offers a plethora of basic types ( number, text, checkbox, radio ) as well as the newer and quite fantastically clever types ( email, color, date, month, search) — and though the Web community at large is wholly grateful for these additions, it does tend to accentuate the fact that the spec has not addressed some of the failings that plague the foundation.</p><h3><strong>Other Tags Beyond Input</strong></h3><p>A general grievance of anyone building out a form that requires variably long user input or option selection must be that the textarea and select tags exist.</p><p>At face value that doesn’t seem so bad. Developing a <strong>Static Form</strong> and dumping it into a webpage has never been readily difficult regardless of the differences in markup, however, when you’re dealing with a <strong>Dynamic Form </strong>like those most often used in <strong>SPA</strong>s(<strong>S</strong>ingle <strong>P</strong>age <strong>A</strong>pplications) you will begin to understand some of the issues that, all of a sudden, become prominent and aggravating.</p><p>Probably the biggest and most common use case is to populate a form, or partial form, based on the option chosen from within a select box. Outside of libraries(like JQuery and its ilk) it is unusually difficult to grab all the information from the currently selected element.</p><p>HTML</p><pre>&lt;select id=”sBox”&gt;<br> &lt;option value=”1&quot;&gt;First Option&lt;/option&gt;<br> &lt;option value=”2&quot;&gt;Second Option&lt;/option&gt;<br> &lt;option value=”3&quot; selected&gt;Third Option&lt;/option&gt;<br>&lt;/select&gt;</pre><p>JS</p><pre>let sBox = document.querySelector(&quot;#sBox&quot;);<br>  console.log(sBox.value);<br>  console.log(sBox.selectedIndex);<br>  console.log(sBox.options[sBox.selectedIndex].textContent)</pre><pre>// 3<br>// 2<br>// Third Option</pre><p>Though the value points to the correct place and selectedIndex is readily available there isn’t any way to grab the associated element from within the list. Unfortunately sBox.options[sBox.selectedIndex] seems to be the quickest and most common way to do this and it’s quite verbose for what it does. The probable response to this might be that value and textContent may in fact relay the same information, however, more and more consistently I find that value is often related to Database Identifiers while the text itself serves as a description for the selection. I can’t help thinking that a simple getSelected method that returned the Option Element selected would do wonders for working with the Select Object, and though I haven’t researched the whole of the situation, given that it nests Options within itself, if it were at all possible I would suggest migrating it into an input type.</p><p>textarea offers another brand of inconsistency, though perhaps one a bit more justified given the reasoning behind it.</p><p>Firstly, in regards to markup,textarea is different from other elements used within forms. Though the property value returns the text within the element, <em>setting</em> that value within markup does absolutely nothing.</p><pre>&lt;textarea value=&quot;hi&quot;&gt;&lt;/textarea&gt; </pre><p>Unlike any other user input element the initial value to be set is explicitly declared between it’s opening and closing tags.</p><pre>&lt;textarea&gt;hi&lt;/textarea&gt;</pre><p>I will admit, although inconsistent, it does make sense with a multi-line value and isn’t all that troubling. There are more important changes that I would like to see <em>but</em> I do think that with the advent of the multi-line strings it is entirely possible to change this:</p><pre>&lt;textarea&gt;<br>hi.<br>how are you.<br>&lt;/textarea&gt;</pre><p>into this:</p><pre>&lt;input type=&quot;textarea&quot; value=`<br>hi<br>how are you<br>`&gt;</pre><p>You probably noticed that the above reduces the textarea tag into an input type — I know that initially might look strange but there is reasoning behind it.</p><p>When textarea was designed and implemented(before the w3c was created to steer the direction of the web) it was, as we can all imagine, to allow for further input outside from a single line of text — but more importantly to prevent the input element with type text from having errors associated with trying to force the functionality of multi-line into its growing list of responsibilities.</p><p>From the literal document titled “Internet Draft” circa Nov. 28th, 1994:</p><blockquote>“NOTE: In the initial design for forms, multi-line text fields were supported by the Input element with TYPE=TEXT. Unfortunately, this causes problems for fields with long text values. SGML’s default (Reference Quantity Set) limits the length of attribute literals to only 240 characters. The HTML 2.0 SGML declaration increases the limit to 1024 characters.”</blockquote><p>(source: <a href="https://tools.ietf.org/html/draft-ietf-html-spec-00">Internet Draft </a>)</p><p>I can’t help feeling that the migration of the functionality to the textarea frominput was justified, but I’m curious if, after all this time( coming up on 2 dozen years since ), it isn’t possible to retrieve that functionality and place it back inside the input object. The character limit does not appear to be relevant any longer and an input type of textarea would resolve issues regarding the iteration and serialization of forms without much hassle. In fact I would find it sensible that given a long enough deprecation timeline the textarea element itself would be better off removed from the w3c spec.</p><h3><strong>Returning Values Outside of Submit</strong></h3><p>Something that I run into quite frequently is the inability to pull important values from input elements with any consistency. There is no simple way to iterate over a Form and grab the most relevant information without branching instructions. Let’s look at the following HTML for instance:</p><pre>&lt;input type=&quot;text&quot; value=&quot;This is Input Text&quot;&gt;<br>&lt;input type=&quot;checkbox&quot; checked&gt;</pre><p>Not too difficult to understand — you have a text box with an assigned value of <em>“This is Input Text” </em>and a checkbox that renders as <em>checked</em>.</p><p>Now, as a rational and intelligent human being, you may gather that referencing the presumed ubiquitous value property would be the obvious way to get what you need out of the above form — but lets take a look:</p><pre>document.querySelectorAll(&quot;input&quot;).forEach(ele =&gt; console.log(ele.value));<br>// &quot;This is Input Text&quot;<br>// &quot;on&quot;</pre><p>Given your experience you might say <em>“Oh! That’s strange!”</em> or <em>“Yes, Zak, obviously that’s what happens! So?”</em> — Either way, what’s the big deal, right?</p><p>Bear with me for a moment. As with <strong>Other Tags</strong>, on the face of it, it doesn’t seem so bad. The checkbox input value returns either &quot;on&quot; or &quot;off&quot; depending on the checked or unchecked state of the box, right?</p><p>Actually no. That would be intuitive but that’s not the case. The value of a checkbox, whether it’s checked or not, is always on unless directly manipulated by setting the value property to something else. This is the value that is received during Server processing of the submitted form and it isn’t intended to reflect whether a box is checked or unchecked. <em>“But Zak, why isn’t it just empty initially? Why does it start out with a value of ‘on’?”</em></p><p>That’s the money question. I have no idea. It doesn’t seem to make sense, does it? If its intended purpose is to simply be a submission value then truly it should be empty if no value is set, but it isn’t. It is as though someone took a step towards reflecting state within the value property and then turned tail and forgot about it.</p><p>If that’s not confusing enough, most often( I’d say a hefty 95% of the time) Developers aren’t looking for a String anyway — they’re looking to return a Boolean of whether or not the box is checked. Were the value to change with state, wouldn’t you know it, it would be easy enough(though ugly)to turn into a Boolean value by interpreting the string like so:</p><pre>let chkbx_bool = (ele.value === &quot;on&quot;) ? true : false;</pre><p>But again, that’s not the case, and the value property does have a purpose, however badly structured I personally may find it to be.</p><p>There is an alternative that I’m sure a lot of you know I’m getting to. That alternative is the checked property that is available on input types of checkbox and radio. It has the wonderful ability to return a Boolean value automatically based on the state of the element(<em>checked or unchecked)</em>.</p><p>A quick example:</p><p>HTML</p><pre>&lt;input id=&quot;chkbx&quot; type=&quot;checkbox&quot; checked&gt;<br>&lt;input id=&quot;rdo&quot; type=&quot;radio&quot;&gt;</pre><p>JS</p><pre>let chkbx = document.querySelector(&quot;#chkbx&quot;);<br>let rdo = document.querySelector(&quot;#rdo&quot;);</pre><pre>console.log(chkbx.checked); // true<br>console.log(rdo.checked); // false</pre><p>This solution is very simple and because of this you may be fooled into believing we’re all set — but context is everything. A form full of one type of input is easy to iterate over but rare. Given a form full of multiple different types of inputs, which is most <em>every</em> form, we’re again saddled with inconsistency.</p><p>Being optimistic, even though it is inconsistent, since we can gather that most input types either have their important values within their value or checked properties, we might be able to use a simple <strong>Short-Circuit Evaluation</strong> to retain the wanted value, like so:</p><p>HTML:</p><pre>&lt;input type=&quot;text&quot; value=&quot;hello hello&quot;&gt;<br>&lt;input type=&quot;checkbox&quot; checked&gt;</pre><p>JS:</p><pre>document.querySelectorAll(&quot;input&quot;).forEach(ele =&gt; {<br>  console.log( ele.checked || ele.value );<br>});</pre><pre>// &quot;hello hello&quot; <br>// true</pre><p>“Yeah! It works!” says optimistic you, but <em>no</em>. Again, it doesn’t.</p><blockquote>“Appearances can be disorienting and a broken clock may always right if you don’t know what time it is.”</blockquote><p>In this particular example we’ve gotten the desired result but the means are entirely wrong. Let me prove it. We’ll simply have the checkbox unchecked on render:</p><p>HTML</p><pre>&lt;input type=&quot;text&quot; value=&quot;on&quot;&gt;<br>&lt;input type=&quot;checkbox&quot;&gt;</pre><p>JS</p><pre>document.querySelectorAll(&quot;input&quot;).forEach(ele =&gt; {<br>  console.log( ele.checked || ele.value );<br>});</pre><pre>// &quot;hello hello&quot; <br>// &quot;on&quot;</pre><p>Foiled again — Short-Circuit Evaluation relies on accepting the first truthy value. Because the checkbox is <em>unchecked </em>the checked property is <strong>false</strong>. This wouldn’t be a deal-breaker except that it does, in fact, have a value of &quot;on&quot; and that value is subsequently returned.</p><p><strong>Side-Note: </strong>For some unknown reason the text input also has a checked property but it is always set to <strong>false</strong>. This isn’t a major issue but it may be a <em>gotcha</em> in a one-off snippet somewhere.</p><p>How can we get this to work then? The solution is really to separate the elements by type. This leaves you with wonderful, and somewhat simple, branching code:</p><pre>document.querySelectorAll(&quot;input&quot;).forEach(ele =&gt; {<br>  if(ele.type === &quot;checkbox&quot;) { <br>   console.log(ele.checked);<br>  }<br>  else if(ele.type === &quot;text&quot;) {<br>   console.log(ele.value);<br>  }<br>});</pre><pre>// &quot;hello hello&quot;<br>// false</pre><p>Obviously this can begin to branch out even further and become a bit unruly and cumbersome if you have to service other types like radio, number, etc</p><p>The best way to manage this would be to populate a <strong>Switch Statement </strong>instead of if/else-if blocks.</p><pre>document.querySelectorAll(&quot;input&quot;).forEach(ele =&gt; {</pre><pre>  switch(ele.type) {<br>  case &quot;date&quot;:<br>  case &quot;color&quot;:<br>  case &quot;text&quot;:<br>    console.log(ele.value);<br>  break;<br>  case &quot;checkbox&quot;:<br>  case &quot;radio&quot;:<br>    console.log(ele.checked);<br>  break;<br>  }</pre><pre>});</pre><p>It doesn’t seem so terrible — in fact, it’s rather pristine and maintainable if a hassle to remember what should be returned by each type. Unfortunately this isn’t the end of our cascading code.</p><p>In the above section titled <strong>Other Tags Beyond Input </strong>I went over the select and textarea elements, discussed their faults, and gave ways in which I believe they could be improved. They are often used in forms, and if we are to iterate over a Form we are going to need to retrieve their values as well. This raises our complication level slightly and introduces some code spaghetti into the mix.</p><p>Up until this point the query that we have been utilizing is simply selecting all the input elements and looping through them one at a time. To include the select and textarea we could create a new loop with a new query, but to keep things compliant with the DRY principle(<strong>D</strong>on’t <strong>R</strong>epeat <strong>Y</strong>ourself), we would do well to just include it in the current loop and separate by the tagName property of the current element.</p><p>The real question is if it would be better to use an if/else-if block or a new switch statement to direct the program flow.</p><p>According to Chapter 7 of the book <strong>Writing Efficient JavaScript </strong>by <a href="http://archive.oreilly.com/pub/au/3902">Nicholas C. Zakas</a>:</p><p>Use the if statement when:</p><ul><li>There are no more than two discrete values for which to test.</li><li>There are a large number of values that can be easily separated into ranges.</li></ul><p>Use the switch statement when:</p><ul><li>There are more than two but fewer than 10 discrete values for which to test.</li><li>There are no ranges for conditions because the values are nonlinear.</li></ul><p><strong><em>Side-Note</em></strong><em>: </em>In case you’re wondering why the switch statement is slated to be used in situations with up to 10 conditions there <em>is</em> a third option that Nicholas articulates in the Chapter(<a href="http://archive.oreilly.com/pub/a/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html">read here</a>) that involves using <strong>Array Lookup </strong>which is quicker than switch in that circumstance. In fact from his points we can infer that <strong>Object Value</strong> <strong>Mapping </strong>would also be a valid approach, but these are both outside the scope of this article. I’ll link to external information within the Resources Section.</p><p>Again, Nicholas gives wonderful advice, though a bit wordy and, as with everything, completely contextual. We’re going to be branching off into a switch no matter what we use to differentiate tag names so you have to wonder how microscopic in our optimization we want to be for such a small win. In the end it’s up to your <strong>discretion </strong>and there isn’t necessarily a right answer as long as the result is clear and maintainable.</p><p>HTML:</p><pre>&lt;input type=&quot;text&quot; value=&quot;whatever&quot;&gt;<br>&lt;select&gt;<br>  &lt;option value=&quot;hi&quot;&gt;Hello&lt;/option&gt;<br>  &lt;option value=&quot;bye&quot;&gt;GoodBye&lt;/option&gt;<br>&lt;/select&gt;<br>&lt;textarea&gt;hi my name is...&lt;/textarea&gt;</pre><p>If/Else-If:</p><pre>document.querySelectorAll(&quot;input, select, textarea&quot;).forEach(ele =&gt; {<br>  if (ele.tagName === &quot;SELECT&quot;) {<br>    console.log(ele.value, ele.options[ele.selectedIndex].textContent);<br>  } else if (ele.tagName === &quot;TEXTAREA&quot;) {<br>    console.log(ele.value);<br>  } else if (ele.tagName === &quot;INPUT&quot;) {<br>    switch (ele.type) {<br>      case &quot;date&quot;:<br>      case &quot;color&quot;:<br>      case &quot;text&quot;:<br>        console.log(ele.value);<br>        break;<br>      case &quot;checkbox&quot;:<br>      case &quot;radio&quot;:<br>        console.log(ele.checked);<br>        break;<br>    }<br>  }<br>});</pre><pre>// whatever<br>// hi hello<br>// hi my name is...</pre><p>Switch:</p><pre>document.querySelectorAll(&quot;input, select, textarea&quot;).forEach(ele =&gt; {<br> switch (ele.tagName) {<br>  case &quot;SELECT&quot;:<br>   console.log(ele.value, ele.options[ele.selectedIndex].textContent);<br>   break;<br>  case &quot;TEXTAREA&quot;:<br>   console.log(ele.value);<br>  case &quot;INPUT&quot;:<br>   switch (ele.type) {<br>    case &quot;date&quot;:<br>    case &quot;color&quot;:<br>    case &quot;text&quot;:<br>     console.log(ele.value);<br>     break;<br>    case &quot;checkbox&quot;:<br>    case &quot;radio&quot;:<br>     console.log(ele.checked);<br>     break;<br>   }<br> }<br>});</pre><pre>// whatever<br>// hi hello<br>// hi my name is...</pre><p>Either way works, and though, as an example, the “date” value may not return quite as we’d like it to be formatted that’s not a problem with the spec, simply Developer preference, and that’s to be expected and dealt with individually.</p><p>There is still a pretty big hinderance in our code. The radio input, as you may have guessed, is a strange case. At the moment we have the value being displayed as to whether or not it is checked, but that’s not what we’re looking for, right? Radio buttons are individual parts of a group after all. For instance:</p><p>HTML</p><pre>&lt;input name=&quot;r_group&quot; type=&quot;radio&quot; value=&quot;radiogoogoo&quot;&gt;<br>&lt;input name=&quot;r_group&quot; type=&quot;radio&quot; value=&quot;radiogahgah&quot; checked&gt;<br>&lt;input name=&quot;r_group&quot; type=&quot;radio&quot; value=&quot;radioblahblah&quot;&gt;</pre><p>All of the above buttons are in the group “<em>r_group</em>” and the idea is to grab the value of the selected element, which is the important value in the majority of web applications. Given just the above we can correctly assume that we will be building a new case for the radio type. We can then use the pseudo-selector :checked in addition to the radio group name to pull the appropriate value. Let’s try that:</p><pre>document.querySelectorAll(&quot;input, select, textarea&quot;).forEach(ele =&gt; {<br>  switch (ele.tagName) {<br>    case &quot;SELECT&quot;:<br>      console.log(ele.value, ele.options[ele.selectedIndex].textContent);<br>      break;<br>    case &quot;TEXTAREA&quot;:<br>      console.log(ele.value);<br>    case &quot;INPUT&quot;:<br>      switch (ele.type) {<br>        case &quot;date&quot;:<br>        case &quot;color&quot;:<br>        case &quot;text&quot;:<br>          console.log(ele.value);<br>          break;<br>        case &quot;checkbox&quot;:<br>          console.log(ele.checked);<br>          break;<br>        case &quot;radio&quot;:<br>        let grp_value = document.querySelector(&quot;input[name=&#39;&quot; + ele.name + &quot;&#39;]:checked&quot;).value;<br>          console.log(grp_value)<br>          break;<br>      }<br>  }<br>});<br>// radiogahgah<br>// radiogahgah<br>// radiogahgah</pre><p>Almost! We did receive the correct value, but we received it multiple times. Obviously this is because we are pulling each radio element individually when, ideally, we could simply reference the group itself and pull the one value that’s checked.</p><p>If this sounds like a familiar structure, you’re right! That’s exactly what the select element achieves. <em>Strange</em>, then, that it seems wholly unobtainable within a defined radio group. As with everything else outlined in this article the keyword here is <strong>inconsistency</strong> and it is the source of hurdles that, I believe, are odd in height and placed on a misshapen, winding track.</p><p>A simple solution then, is to only return the value of the radio button <strong>if</strong> it’s checked:</p><pre>case &quot;radio&quot;:<br>         if (ele.checked) console.log(ele.value)<br>         break;</pre><p>Definitely sounds good! <strong>Except</strong>, what if none of them are checked by default and the user doesn’t tap a radio? Then nothing is returned at all. In an Application where you’re expecting a value, whether that’s an empty string, <em>null</em>, or <em>undefined</em>, getting literally nothing isn’t just bad — it means your Application is, at best, severely flawed and, at worst, <strong>broken</strong>. That’s not too good. You could set the requiredattribute to <strong>true </strong>on at least one of the radios, but this will only matter if you’re submitting the form and isn’t applied to form processing without submission.</p><p>There are a few options of what to do here. We have to keep in mind however, that though our HTML for this example only specifies one group of radio buttons, this code should be reusable for iterating over any form, and any form may include several radio groups. What that means is that we need to keep track of already processed radio groups in a container housed in an external scope. The external scope is necessary so that the container doesn’t simply get redeclared and emptied every time the program loops. I don’t recommend that the external scope used be the <strong>Global( Window ) </strong>scope but, for demonstration purposes, that’s what our code will show.</p><p>We will be using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">Set Object</a> to store the processed groups. It has the methods has and add which either check if an entry is contained within the object or add an entry to the object.</p><p>HTML</p><pre>&lt;input name=&quot;r_group&quot; type=&quot;radio&quot; value=&quot;radiogoogoo&quot;&gt;<br>&lt;input name=&quot;r_group&quot; type=&quot;radio&quot; value=&quot;radiogahgah&quot; checked&gt;<br>&lt;input name=&quot;r_group&quot; type=&quot;radio&quot; value=&quot;radioblahblah&quot;&gt;</pre><pre>&lt;input name=&quot;r_group2&quot; type=&quot;radio&quot; value=&quot;fee&quot;&gt;<br>&lt;input name=&quot;r_group2&quot; type=&quot;radio&quot; value=&quot;fi&quot;&gt;<br>&lt;input name=&quot;r_group2&quot; type=&quot;radio&quot; value=&quot;fo&quot;&gt;</pre><p>JS</p><pre>let r_set = new Set();<br>document.querySelectorAll(&quot;input, select, textarea&quot;).forEach(ele =&gt; {<br> switch (ele.tagName) {<br>  case &quot;SELECT&quot;:<br>   console.log(ele.value, ele.options[ele.selectedIndex].textContent);<br>   break;<br>  case &quot;TEXTAREA&quot;:<br>   console.log(ele.value);<br>  case &quot;INPUT&quot;:<br>   switch (ele.type) {<br>    case &quot;date&quot;:<br>    case &quot;color&quot;:<br>    case &quot;text&quot;:<br>     console.log(ele.value);<br>     break;<br>    case &quot;checkbox&quot;:<br>     console.log(ele.checked);<br>     break;<br>    case &quot;radio&quot;:<br>     if (r_set.has(ele.name)) break;<br>     else {<br>      r_set.add(ele.name);<br>      let checked = document.querySelector(&quot;input[name=&#39;&quot; + ele.name + &quot;&#39;]:checked&quot;);<br>      console.log((checked) ? checked.value : &quot;&quot;);<br>     }<br>     break;<br>   }<br> }<br>});<br>r_set.clear();</pre><pre>// radiogahgah<br>// &quot;&quot;</pre><p>It works! This time, it really does! That’s marvelous — except it’s clearly a bit ridiculous that something should be so complex when searching for rudimentary output.</p><p><strong>A Temporary Immediate Solution</strong></p><p>Over the course of this article I have outlined a few areas of concerns about the state of HTML Forms. There are others(a.e. an easy way to save or load values from client side storage/ a better way to match patterns ). These are all ideas that I doubt will be addressed with any expediency as they’ve become mostly expected and, no doubt, have long-standing platforms that have adapted to their inelegance.</p><p>Currently I have a solution that extends the DOM to make things a bit easier when manipulates forms. It can be found here:</p><p><a href="https://github.com/zfrisch/Input-Management">zfrisch/Input-Management</a></p><p>It’s a small Input Management “Library” that does the following:</p><ul><li>From any Container(<em>form, div, section, or even the document.body</em>) render an object that allows easy access to the most important values. This is done through the method getChildInputValues which is appended to every HTML Element and thus accessible from every HTML Element.</li></ul><pre>let container = document.getElementById(&quot;myContainer&quot;);<br>let inputObject = container.getChildInputValues();</pre><ul><li>Using the above object you can use the methods:</li></ul><p>getByName, getByID, getByText, getByType, getByValue, or getByGroup to return a specific input object containing what you need. This means that every single object will have a value and that value is the <em>most important</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*01dJZ_pETVzBHm_Tl-F1OQ.png" /><figcaption>List of Important Values</figcaption></figure><p><strong>Note: </strong><strong>getByGroup </strong>will return an object that contains the value of the radio group.</p><ul><li>There is also an iterable array of input objects that you can access by using thefields method.</li></ul><p>By altering the inputs in this example you’ll see the changes reflected from the methods being called in real time:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FwPLdje%3Fheight%3D600%26slug-hash%3DwPLdje%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fpen%2FwPLdje&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/38dc95d218f4e265416b48971322e16a/href">https://medium.com/media/38dc95d218f4e265416b48971322e16a/href</a></iframe><ul><li>Additionally any input that is grabbed from the Container is automatically setup into an easy-to-store JSON String, aptly underneath the property storable . This can be sent out with an XHR request, stored in Client Storage, or simply kept on-hand as easily accessible data.</li></ul><pre>// storing all inputs and their values in storage</pre><pre>let container = document.getElementById(&quot;container&quot;);<br>let InputObject = container.getInputChildValues(); localStorage.setItem(&quot;form&quot;, InputObject.storable);</pre><ul><li><strong>Saving</strong> form data like this is great but what’s more is that you can <strong>load</strong> this data from storage very easily using the method renderUsingInput on any Container.</li></ul><pre>// getting all values and rendering them<br>let container = document.getElementById(&quot;container);<br>let RetrievedInput = localStorage.getItem(&quot;form&quot;);<br>container.renderUsingInput(RetrievedInput);</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fembed%2Fpreview%2FBmxZzG%3Fheight%3D600%26slug-hash%3DBmxZzG%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fzfrisch%2Fpen%2FBmxZzG&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F237873.BmxZzG.small.23c4ddda-7420-445a-ab1a-533b6b05b4d5.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/272884637a7a6134c2d92c0bae3bd45f/href">https://medium.com/media/272884637a7a6134c2d92c0bae3bd45f/href</a></iframe><p><strong>Note: </strong>For the values to be properly loaded into their appropriate inputs, the inputs <em>must contain</em> the same attributes that they had when the values were stored(<em>id, class, name of all inputs must be the same as they were </em><strong><em>at the time</em></strong><em> they were stored)</em></p><p>As much as I use this code, keep in mind that this library isn’t meant to be perfect for every situation. There are quite a great deal of cases(<em>literally</em>)that are not implemented into it, but as a general tool I believe it works quite well as demonstrated above. It’s also perfectly viable to extend over time without too much trouble. I offer that if you do use it and either find fault, or implement a needed extension, please feel free to make the appropriate requests on my Github Project Page and I’ll respond/add appropriate extensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*86TI3abvO2lGxiok.png" /></figure><p>Describing the state of HTML Forms is very much opinion. I have a lot of appreciation for what the <strong>w3c </strong>have accomplished in standardizing a lot of features over the last decade. Still, if you have at all stuck your foot into the world of Web Development you have probably overcome some of the hurdles mentioned in the above article, and I obviously think that’s worth bringing into focus.</p><p>There are a lot of cool things coming along down the pipe or already here, and though I am intrigued and excited for these new tools and features, I sometimes find myself wondering if we’re building onto the penthouse while ignoring the foundations.</p><p><strong>Resources:</strong></p><p><a href="https://github.com/zfrisch/Input-Management">zfrisch/Input-Management</a></p><p><a href="http://archive.oreilly.com/pub/a/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html">Writing Efficient JavaScript Excerpt</a></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">Map - JavaScript | MDN</a></li><li><a href="https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value">How to get a key in a JavaScript object by its value?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d61ffd9d9ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Function Composition, Currying, and Partial Application]]></title>
            <link>https://medium.com/wdstack/javascript-function-composition-currying-and-partial-application-5a04107530ee?source=rss-b77bb94966c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a04107530ee</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Zak Frisch]]></dc:creator>
            <pubDate>Tue, 21 Nov 2017 18:48:20 GMT</pubDate>
            <atom:updated>2017-12-07T10:18:16.911Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick guide</h4><p>The concepts of <strong>Currying </strong>and<strong> Partial Application </strong>are useful to anyone who is willing to learn them regardless of their level of experience. They will open the door to <strong>Function Composition</strong> — which is a fancy way of saying you can use a function to call another function and make things happen. You can almost think of the concept like Russian Nesting Dolls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/0*Dc-0JkN2TXdjQCuO.jpg" /></figure><p>A quick example of this would be the following:</p><pre>let arr = Array(5);</pre><pre>function getLength(array) { <br>  return array.length; <br>};</pre><pre>function showLength(length) { <br>  alert(length);<br>};</pre><pre>showLength( getLength( arr ) ); // alerts 5</pre><ul><li>getLength processes arr</li><li>getLengthreturns the length value to showLength</li><li>showLength shows the value using alert.</li></ul><p>Now, as you might have noticed, the above example is really rather useless. It’s the concept that’s important. For those who are familiar with U.S. History part of the Industrial Revolution was brought about by <strong>Interchangeable Parts</strong>. The idea of interchangeable parts means that if you buy an incandescent light-bulb from Company <em>A </em>and decide that years later you want to replace it with a fluorescent light-bulb from Company <em>B</em> you don’t have to redo the wiring of the light fixture. Both light-bulbs will fit the threading and accept the standard volts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*bJfOotD2LdGBNmpbaRVv0g.png" /><figcaption>changing a light-bulb in an alternate reality</figcaption></figure><p>In the previous example I used alert to create a pop-up on the screen. What if, a few weeks after this application is built, I no longer want to have a pop-up for this particular page, but instead I want to log the information to the console? I could change the code of the showLength function, but if I had used the function anywhere else it might break other parts of the application. This is where the beauty of <strong>Function Composition</strong> comes into play. Instead of breaking the application or creating a conditional statement to manage whether or not the information should be alerted or logged, I can write a new function and easily replace the name of the function being called:</p><pre>let arr = Array(5);</pre><pre>function getLength(array) { <br>  return array.length; <br>};</pre><pre>function showLength(length) { <br>  alert(length);<br>};</pre><pre>function logLength(length) {<br> console.log(length);<br>};</pre><pre>logLength( getLength( arr ) ); // logs 5;</pre><p><strong>Function Composition</strong> is simply the idea of taking multiple functions and combining them together to create a result that can be easily maintained. As easily as swapping parts!</p><h4>Currying vs Partial Applications</h4><p>Currying and Partial Applications are very similar concepts and they are often confused with one another. <em>Why?</em> Well, because the code that produces either is almost identical and even veteran Developers will misuse the terms often enough that they become almost synonymous. Plus the definition you’re likely to find describing the differences is, like a lot of explanations in Computer Science, exceedingly verbose:</p><blockquote>A call to a partially applied function returns the result right away, not another function down the currying chain; this distinction can be illustrated clearly for functions whose arity is greater than two.</blockquote><blockquote>Thus, any partial application may be reduced to a single curry operation. As such, curry is more suitably defined as an operation which, in many theoretical cases, is often applied recursively, but which is theoretically indistinguishable (when considered as an operation) from a partial application.</blockquote><blockquote>So, a partial application can be defined as the objective result of a single application of the curry operator on some ordering of the inputs of some function.</blockquote><p>(citing <a href="https://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application">WikiPedia</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FM-5WHHDtyHDIxfon-zpFQ.jpeg" /><figcaption>What?</figcaption></figure><p>It’s a bit disarming at first. I hate to say it, but you do get used to long, winding, and seemingly ridiculous sentences when you’ve been around long enough in any area of Technology. As always I would be lying if I said I didn’t have contempt for the practice of making simple concepts unintelligible to the layman. A person trying to understand a concept shouldn’t have to look up pieces of what they’re reading and stitch them together themselves — it should be laid out <strong>as clearly as possible</strong> by the Teacher.</p><blockquote>The person trying to understand a concept shouldn’t have to look up pieces of what they’re reading and stitch them together themselves— it should be laid out as clearly as possible by the Teacher.</blockquote><p>Without further ado we’re going to create a simple addition function to quickly explore the concepts of <strong>Currying</strong> and <strong>Partial Application </strong>and their differences. Let’s take a look!</p><p><strong>Normal Addition Function</strong></p><pre>function addition(x, y) {<br> return x + y;<br>}<br>addition(5, 6); // 11</pre><p>The above function is, hopefully, very easy to read. In the interest of clarity here’s a play by play:</p><ul><li>We declare a function called addition</li><li>The function has two parameters that it takes. These are named x and y.</li><li>When the function is passed two parameters we return the two parameters( x and y) added together.</li><li>We show an example of calling the function with the parameters 5 and 6 . This results in a returned value of 11</li></ul><p>What would this look like if we were to write this as a currying function? Let’s take a look at the completed function and then go through a quick explanation.</p><p><strong>Currying Addition Function:</strong></p><pre>function currying_addition(x) {<br>  return function(y) {<br>   return x + y;<br>  }<br>}</pre><pre>currying_addition(5)(6); // 11</pre><p>The above may be confusing at first. It happens, but no worries! I will walk you through it!</p><ul><li>We declare a function called currying_addition</li><li>Our currying_addition function takes <strong>one</strong> parameter, x</li><li>We immediately return an <strong>Anonymous Function</strong>( an Anonymous Function is a function declaration without a name )</li><li>The Anonymous Function takes <strong>one</strong> parameter, y</li><li>The Anonymous Function returns the value of x + y</li><li>We perform a call on currying_addition with the parameter 5 and then call the returned function using the parameter 6 — this returns 11</li></ul><p>What’s important to realize about <strong>Currying</strong>(and if you have a keen eye you may have noticed this already) every function call only requires <strong>one </strong>parameter. In more technical terms they are all <strong>Unary Functions</strong> (<em>unary is a simple way to say </em><strong><em>one</em></strong><em>, and when we’re talking about a function we’re referring to the number of parameters it has).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*4ktAo8RMsoLr1DqvLK9MzA.png" /><figcaption>How not to win Uno</figcaption></figure><p><strong><em>Note: </em></strong>While programming you may have heard the terms <strong>Binary</strong> or <strong>Ternary</strong> — these all have different meanings depending on what we’re referring to, but if you see the word <strong>Binary</strong> you know that that there are <strong>two</strong> of something, if you read <strong>Ternary</strong> you know that there are <strong>three </strong>of something. These descriptors are called <strong>Numerical Notation </strong>and when we apply them to functions (<strong>unary function, binary function, ternary function</strong>) we’re referring to the number of parameters that a function takes. If there is no set number of parameters the function is described as <strong><em>polyadic</em></strong><em> </em>or, more commonly,<em> </em><strong><em>variadic</em>.</strong></p><p>Another way of stating the number of parameters a function has is to simply state that it has an <em>Arity</em> of 1, or an <em>Arity </em>of 2, or an <em>Arity </em>of 3, etc. <strong>Arity </strong>is a term that directly correlates to the number of parameters so whether you’re saying “<em>Raphael, this function has an </em><strong><em>arity</em></strong><em> of 1!</em>” or “<em>Raphael, this is a </em><strong><em>unary function</em></strong><em>!</em>” you’re saying the same thing, assumed pomposity aside.</p><p><strong>Currying </strong>can be readily described: <em>the process of composing multiple single-parameter functions until a result is achieved.</em></p><p><em>Note: Currying often utilizes </em><strong><em>Recursion — </em></strong>for more information on that please take a look at my <a href="https://medium.com/@zfrisch/understanding-recursion-in-javascript-992e96449e03">Understanding Recursion in JavaScript</a> article.</p><p>Okay, so that’s currying! If you’re still a bit confused on it I’ll post some reference articles in the <strong>Resources</strong> section that you can look over. (fyi I <em>HIGHLY </em>recommend Douglas Crockford’s seminar within Front End Masters. It’s fantastic!) Don’t worry if it’s a little difficult to understand initially. Sometimes concepts take a bit to “click” — but once they do they’re invaluable!</p><p>So how would the Addition function look using <strong>Partial Application</strong> ? Let’s see!</p><p><strong>Partial Application Function:</strong></p><pre>function add(x, y) {<br> return x + y;<br>}</pre><pre>function partial_application(y) {<br>  return add(3, y);<br>}</pre><pre>partial_application(8); // 11</pre><p>The Step-By-Step:</p><ul><li>We declare a function called add</li><li>The function has two parameters that it takes. These are named x and y.</li><li>When the function is passed two parameters we return the two parameters( x and y) added together.</li><li>We declare a function called partial_application</li><li>partial_application has a single parameter. This parameter is named y</li><li>The function calls and returns the add function with 3 as the first parameter and y as the second</li><li>As an example partial_application is called with a parameter of 8 and returns the value 11</li></ul><p>This may be a little more confusing than our previous example for the simple reason that there are more parts, though I promise it’s not as complicated as it may seem. We setup an add function and a partial_application function. The partial_application function calls add with a 3 parameter and a y parameter. The function’s only job is to return a value from a <em>partially applied</em>add function.</p><p>Allow me to reiterate as I feel like that is the biggest hurdle to understanding <strong>Partial Application</strong>. The concept means to <em>Partially Apply</em>. This seems obvious, but in the field of Technology the word <strong>Application</strong> clearly has an alternative meaning and when you initially come across the term you would be forgiven for instinctively assigning the wrong meaning to the word.</p><p>The way that we are to look at it is this: let’s say Hugo works at the Pool applying sun-tan lotion to people(<em>that’s a job, probably</em>). When he comes into work he finds out that the person on the previous shift, a real nutter named Lenny, applied lotion to only the left side of all the sunbathers. In shock at the lack of symmetry Hugo hurriedly applies sun-tan lotion to the right side of all the sunbathers to make sure they are fully covered.</p><p>In this example Hugo is the partial_application function and Lenny the add function within the partial_application function. Lenny already has half of each person done, but none of them were fully applied until Hugo came into work and finished up the job.</p><p>In the code example above, theadd function has the value3pre-applied by our partial_application function, and though it only takes the one parameter(a <strong>unary</strong> <strong>function </strong>is not explicitly tied to <strong>currying</strong>) since it is taking that parameter and using it along with the already <em>Partially Applied </em><em>add </em>function we consider it <strong>Partial Application</strong>.</p><h3>Resources</h3><ul><li><a href="https://en.wikipedia.org/wiki/Partial_application">Partial application - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Currying">Currying</a></li><li><a href="https://books.google.com/books?id=PXa2bby0oQ0C&amp;pg=PA43&amp;lpg=PA43&amp;dq=douglas+crockford+currying&amp;source=bl&amp;ots=HKmin9x5mC&amp;sig=P-R5NZXPosD8JAoMWZJwboydIeY&amp;hl=en&amp;sa=X&amp;ved=0ahUKEwjxmeSYqdDXAhVl04MKHUw9C2cQ6AEIUjAG#v=onepage&amp;q=douglas%20crockford%20currying&amp;f=false">JavaScript: The Good Parts</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhRJrp17WnOE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhRJrp17WnOE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhRJrp17WnOE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6665b40fd253d6e7b907e9552f89cffd/href">https://medium.com/media/6665b40fd253d6e7b907e9552f89cffd/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a04107530ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wdstack/javascript-function-composition-currying-and-partial-application-5a04107530ee">JavaScript Function Composition, Currying, and Partial Application</a> was originally published in <a href="https://medium.com/wdstack">WDstack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>