<?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 Lari Maza on Medium]]></title>
        <description><![CDATA[Stories by Lari Maza on Medium]]></description>
        <link>https://medium.com/@larimaza?source=rss-5531a5a889f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hNX2WTou_J0kFousQesrJA.jpeg</url>
            <title>Stories by Lari Maza on Medium</title>
            <link>https://medium.com/@larimaza?source=rss-5531a5a889f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 13:38:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@larimaza/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[How to write good documentation]]></title>
            <link>https://medium.com/larimaza-en/how-to-write-good-documentation-e19c70dc67f0?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e19c70dc67f0</guid>
            <category><![CDATA[software-developer]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[writing-tips]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Thu, 30 Jan 2020 19:23:01 GMT</pubDate>
            <atom:updated>2020-02-04T18:12:23.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHDSnrDxim_3p1ffZiiL9g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/3To9V42K0Ag?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">John Baker</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://medium.com/larimaza-pt/como-escrever-boas-documenta%C3%A7%C3%B5es-b36131d78f7c"><em>[clique aqui para português]</em></a></p><p>I’m a weirdo. I know, that&#39;s a strange way to start an essay, but see — I&#39;m the only person I know who <em>always</em> reads the instruction manual.</p><p>A while ago, I furnished my apartment and my bedside reading became a pile of manuals for house appliances. I enjoyed the refrigerator manual, but thought the ending was a little <em>cold</em> (…sorry).</p><p>Truth is, KitchenAid reader or not, nobody escapes from needing instructions in life and the experience is much more difficult if this document is incomplete or confused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*kUCGCf3-ltaNH_9II4ZTaw.jpeg" /><figcaption>Confusing Ikea instructions for building, well, a Hadron Collider</figcaption></figure><p>In software development and tech, documentation has multiple functions:</p><ul><li>Formalize processes and systems</li><li>Learn out loud</li><li>Help people answer their own questions</li></ul><p>In all cases, both the writer and consumer benefit from the production of the material. If you want to participate in this knowledge exchange, here&#39;s a complete guide on how to write good documentation!</p><h4>Before you start</h4><p>Despite the parallel drawn earlier, making software documentation is much more complex than a device manual. That’s because there is no closed set of instructions that can be printed and never revised. Technology is constantly changing, and the most used systems are the most updated. Therefore, the most important documentation is the one that gets outdated faster.</p><p>That&#39;s nowhere close to encouraging, but it&#39;s remediable: most of the time, it&#39;s not the <em>entire</em> doc that is obsolete at once. It&#39;s the operational, technical details. So, one workaround is to separate the <strong>how</strong> from the <strong>why</strong>. <strong>How</strong> to use the system changes constantly, but <strong>why</strong> the system exists is a much more stable concept.</p><p>That was Etsy&#39;s idea when they did an <a href="https://codeascraft.com/2018/10/10/etsys-experiment-with-immutable-documentation/">experiment targeting “immutable” documentation</a>. Following this concept to the letter involves other tools and making the process more complex, but we can extract a simple and very applicable lesson (TL; DR): whenever possible, avoid very specific details that can change. For example, instead of saying <em>“We use the Roboto font”</em>, you can give instructions to look for the project’s font in the &lt;head&gt; tag of the index.html file.</p><h4>First steps</h4><p>A blank page can be intimidating to the point of paralyzing even the most experienced writer. Here, we have the advantage of being able to start with a defined plan, without having to think too hard. I always follow three steps, in that order:</p><ul><li>Collect reference materials</li><li>List content in macro topics</li><li>Add details and technical part</li></ul><p>Before I started writing the <a href="https://github.com/magnetis/astro">Astro</a> Readme (design system at my former employer), I first opened all the references I would use. Then, I listed the information I already knew the document would need to contain. At that moment, I didn’t care much about the order:</p><pre>Astro Readme</pre><pre>- Instructions for importing the dependency into your project<br>- How to add the sources<br>- How to run the project locally<br>- Where to view online documentation<br>- How to edit the documentation<br>- How to deploy the documentation<br>- Official support for React<br>- Known errors for troubleshooting</pre><p>Now that the page is no longer blank, it&#39;s much easier to proceed by detailing each of these steps. Before that, however, let’s go into detail about the structure of this document.</p><h4>Title and introduction</h4><p>The question you must answer when writing the title and the first paragraph of your doc is: “What is this document for?”</p><p>Try to come up with a title that clearly states what the text is about. If that&#39;s not enough, the first paragraph serves as a support to understand if this document is where they&#39;ll find the information they&#39;re looking for.</p><pre>Mobile Accessibility Guide</pre><pre>This document is a reference guide for recent discoveries and new practices that must be disseminated in our project to continuously improve the accessibility of the mobile app. Right now, our efforts are focused on VoiceOver (iOS) and TalkBack (Android) screen readers.</pre><h4>Steps or items</h4><p>We can now go back to that information list we mapped in the first step. Now&#39;s a good time to try to organize these steps or items in the same order that the reader will need to refer to them. For instance, <em>&quot;Install&quot;</em> and then <em>&quot;Usage&quot;</em>.</p><p>The best way to present the content may vary depending on the type of process to be described. Step-by-step instructions are clearer if numbered; actions with no defined order can be organized into topics; a less technical issue can be well explained with a FAQ, and so on. When in doubt, test more than one format before defining.</p><p>Use very descriptive headings in each of them, to make it possible to quickly find the necessary information. This will also help you create a good index later.</p><h4>Troubleshooting</h4><p>In very technical docs, a <em>&quot;Troubleshooting&quot;</em> section can be especially useful for documenting known errors and obstacles and showing the way around them. It&#39;s important to keep this section up to date, as it&#39;s not uncommon to spend more time trying to fix bugs than actually developing.</p><h4>Contact</h4><p>In most cases, it&#39;s useful to leave contact info to answer questions and send suggestions by the end of the document. If you&#39;re <a href="https://help.github.com/articles/about-readmes/">writing a GitHub Readme</a>, the contact section can also point to how and when to open an issue in the repository.</p><h4>References</h4><p>Including links to the materials used as a reference at the end of the doc is a good practice both for crediting authors and for readers who may be interested in diving deeper into those subjects.</p><h4>Keep in mind</h4><p>While creating this documentation, I suggest that you keep in mind some questions that help you cover as much territory as possible:</p><ul><li><strong>Who will read this documentation — and what&#39;s their technical level?</strong></li></ul><p>Will this doc be consumed by people within a company team, or by the general public in an open source project? It&#39;s necessary to adapt the technical level or detail according to the reader, keeping the text as didactic as possible. Remember that &quot;obvious&quot; is a relative concept; sometimes, we think anyone understands what we consider simple, but this is not always true (I&#39;m looking at you, impostor syndrome).</p><ul><li><strong>Anticipate questions</strong></li></ul><p>That&#39;s basically an empathy exercise: try to anticipate any doubts that may arise throughout the text and answer them in the same place they appear.</p><ul><li><strong>Single source of truth</strong></li></ul><p>The “single source of truth” concept calls for a single location to be maintained as a source of consultation for all matters relating to a subject. It is easier to keep a single place updated, so this is a good practice to aim for.</p><ul><li><strong>Know when to stop</strong></li></ul><p>An unnecessarily long document is difficult to read and maintain. Try to discern how far you&#39;ll explain a topic within the doc or when it&#39;s time to link to a more specialized external tutorial. For more advanced people who may need more details, this is a way to point them in that direction without penalizing others with extra content.</p><ul><li><strong>Stay in scope</strong></li></ul><p>Still on the previous item, be as objective as possible. If a tangent process starts to get too detailed, it may be necessary to separate it into another document.</p><ul><li><strong>Link, don’t replicate</strong></li></ul><p>Avoiding details that can easily change dramatically decreases the frequency with which the document will be outdated. If the shifting details can be found in a more up-to-date external source (for example, information about a third-party plugin or dependency), it is better to link to it than to replicate that content within your documentation.</p><h4>Enriching details</h4><p>So, you covered all the previous points and want to take it a step further? Here are some details that enrich the experience of those who consume your doc.</p><ul><li><strong>1 reference = 1 link</strong></li></ul><p>Whenever you reference a concept or process, e.g. <a href="https://www.markdownguide.org/">Markdown</a>, find material on that subject and insert a link. Thus, a person who does not know exactly what that is or wants details can learn from a source you selected, which guarantees that you will be on the same page.</p><ul><li><strong>Illustrate</strong></li></ul><p>Screenshots, gifs, illustrations, graphics, memes… Choose the best way to illustrate the content and use as many figures as necessary to make the text more dynamic and didactic.</p><ul><li><strong>Information hierarchy</strong></li></ul><p>Those in contact with design are already familiar with this concept: the idea is to establish a visual hierarchy to facilitate quick understanding and localization of information. The most useful application here is to explore text formatting to create levels of title and subtitle (such as h1 to h6 headings in HTML), and thus to group macro and micro sets of information. We can also use bold, italics and even colors (like red in points of attention) to add intonation to the text, just as we would in voice speech.</p><ul><li><strong>Practical examples</strong></li></ul><p>Whenever possible, add an example of the process described to illustrate its application in practice. This will always make all the difference in message clarity.</p><h4>All done, now what?</h4><p>Hold the urge to click “Publish”! Now’s the time to groom and polish your doc. Bear with me, it&#39;s just a few more steps:</p><ul><li><strong>Read from beginning to end</strong></li></ul><p>When writing, it&#39;s normal to go back and forth several times and change paragraphs. Reading from beginning to end helps to review the cohesion of the text flow without interruption.</p><p>Time to drop a super important writing tip: the vast majority of people don’t read, they<strong> scan</strong>. Therefore, it&#39;s necessary to test the effectiveness of that information hierarchy, checking if it&#39;s possible to jump directly to a topic in the middle of the text and understand what is happening there. That’s what most people will do in your doc, no matter how good it is.</p><ul><li><strong>Edit</strong></li></ul><p>When proof reading, in addition to finding improvement points, you should also wipe down, summarize and cut redundant or unnecessary parts. Remember: people don&#39;t read everything, so less excess is more clarity.</p><ul><li><strong>Create the index</strong></li></ul><p>The index, or <em>“Table of contents”</em> as many call it, facilitates the preview of the content and also allows quick navigation. If the tool allows anchors (links that lead to points on the same page), use them.</p><ul><li><strong>Ask for reviews</strong></li></ul><p>Ask people familiar with the documented system to review it, so they can validate that you have covered all points and have not forgotten anything. Then ask <strong>unfamiliar </strong>people. This is the most important part of simulating how a new person will understand the documentation, and is usually where you&#39;ll get the most feedback.</p><ul><li><strong>Always update</strong></li></ul><p>After publishing the doc, it’s easy to forget about it forever. Technology documentation is never finished; the best practice is to elect a person or group responsible for maintaining it.</p><p>Another great trick for keeping docs updated is asking newcomers to contribute. They will read and use all those instructions for the first time, so that&#39;s a great opportunity to spot any outdated or missing info and improve them.</p><h4>Final reminder</h4><p>It&#39;s important to have well-written and updated documentation, but the software itself is even more important. We don’t want to get lost in detail and forget what our priority is, as the Agile manifesto preaches:</p><blockquote>Working software over comprehensive documentation.</blockquote><p>This priority is especially valid in the context of a closed company. But, of course, in a public or open source project, this motto has its caveats. After all, without documentation, it&#39;s very hard to understand third party code and impossible to contribute.</p><p>The final reminder is to always adapt the level of dedication to the documentation according to its context.</p><p>That&#39;s all for today and see you next time ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19c70dc67f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/how-to-write-good-documentation-e19c70dc67f0">How to write good documentation</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DX: Developer Experience in Design Systems]]></title>
            <link>https://medium.com/larimaza-en/dx-developer-experience-in-design-systems-165825b12cda?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/165825b12cda</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[dx]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Tue, 28 Jan 2020 23:29:34 GMT</pubDate>
            <atom:updated>2020-01-30T19:26:15.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fj9dGu1qXubavTfJ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@joeel56">Nicole Wolf</a></figcaption></figure><p><a href="https://medium.com/larimaza-pt/dx-developer-experience-em-design-systems-1ff507f216ee"><em>[clique aqui para português]</em></a></p><p>DX, or Developer Experience, is a discipline that describes the experience of a developer using a product. In a similar way to UX (User Experience), a good DX makes all the difference in your product’s reach potential, be it an API, a library, a tool or a service. The awareness on this subject has grown so much that there is even specialized work — dev <a href="https://medium.com/u/c2509fce86ff?source=post_page-----1ff507f216ee----------------------">Sarah Drasner</a>’s Twitter bio says <em>“Head of DX @ Netlify”</em>.</p><p>In my experience developing <a href="http://astro.magnetis.com.br/">Astro</a>, Magnetis’ design system (my former employer), the quality of DX is very relevant to boost user productivity. These people may or may not be Magnetis employees, since Astro is open sourced — which means that the responsibility is even greater.</p><p>Based on what I learned there, I bring some attention points to improve the DX of your project:</p><h4>1. Documentation</h4><p>It seems somewhat obvious to mention documentation as a main point of attention in DX; but, for an artifact that will often be the only means of communication with the user, it rarely receives the attention it deserves.</p><p>In open or closed projects and repositories, some maintainers expect users to understand everything just by reading the code — which is not only bad communication, but also bad empathy. And within teams, the solution to poorly documented projects is often to ask someone, which is also not productive for both sides.</p><p>Documenting is your opportunity to explain in human language the purpose and how to use your project. Here, you must teach how to use the design system, but also how to contribute to its code (even if it is not open sourced, newcomers might join the project at any time). Think of these moments separately — you can even create two separate files on GitHub, as we did in the <a href="https://github.com/magnetis/astro">Astro repository</a> with “Readme” (usage guide) and “Contributing” (contribution guide).</p><p>I will not go into detail on how to write good documentation because I have already written <a href="https://medium.com/larimaza-en/how-to-write-good-documentation-e19c70dc67f0">an article about it</a>, but, in summary, it should include three things:</p><ul><li>Comprehensive: Make sure the document covers any doubts that may arise about how the project works. Explain what it does, how to install, how to use it, and include solutions to known problems. Your goal here is to eliminate the need to contact you directly to answer any questions. Don’t be a bottleneck. The Single Source of Truth must be the documentation, not you.</li><li>Accessible: Don’t assume that everyone who reads the document has the same technical level as you, even if you think you have a low technical level (I’m looking at you, impostor syndrome). Avoid technical terms when possible. Write step-by-step tutorials. Do not assume that the person knows how to clone a project or install dependencies via terminal, for example. Explain to a beginner and you will be explaining to everyone.</li><li>Friendly: Reading documentation can be a tedious activity, so try not to make it unnecessarily long. There is a difference between comprehensive and wordy. Get to the point, use a friendly tone and, if you want to, you can even add a touch of humor.</li></ul><h4>2. Usage patterns</h4><p>In the case of Astro, the design system is used by applying CSS classes to a markup structure showcased in the documentation. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B-eK_xToJwg5en6I.png" /><figcaption>Astro buttons and their markup structure and CSS classes</figcaption></figure><p>We tried to create class names that are descriptive for humans, instead of something like a-bt--ur__md1, even if they’re longer; we want them to be self-explanatory and memorable, which reduces confusion and the need to consult the documentation repeatedly.</p><p>By the way: this is when you realize you’re doing API design. Neat!</p><p>Another important point is that class names need to be more specific (like a-btn) rather than completely generic (like btn) to avoid conflicts with existing CSS in legacy projects. The objective is to minimize side effects when importing the design system, and this mindset must be applied to all user-facing (the dev being the user here) points of the project.</p><p>Finally, to create a scalable and predictable system, you need to try to maintain a usage pattern that makes sense. This is a big challenge when we receive design demands that are outside the norm, and it may be necessary to negotiate to satisfy these demands while also maintaining consistency.</p><p>For example: in Astro, there are many variants of button styles and each one has four colors. A design system tends to scale, and when new colors or styles are introduced, we wanted to follow the pattern and even make it easier to manipulate these buttons with less visits to the documentation.</p><p>With that in mind, we created a class structure that varies in a predictable way. a-btn--uranus is the primary button in blue (color we called <em>“uranus”</em>). For the other variants, we added a modifier that can be a-btn--outline-uranus for the outline button or a-btn--ghost-uranus for the ghost button.</p><p>Furthermore, the color <em>“uranus”</em> can be replaced with any of the color variants (<em>“mars” </em>for red, <em>“venus”</em> for pink or <em>“earth”</em> for green) in any button and the result is still predictable.</p><p>And to define size, the user must add one of the three size classes: a-btn--small, a-btn--medium or a-btn--large. Regardless of which button, the result is always the same.</p><p>Here’s a video of me playing around with these modifiers (please open in a new tab):</p><p><a href="https://drive.google.com/file/d/1FlsoZ0plt9oqnPxlWyxD0_p1ILq6PNX_/preview">demo.webm</a></p><p>By creating standards and predictability, usage is more intuitive, error-proof and more independent of documentation.</p><h4>3. Technologies</h4><p>Aside from the ground we just covered, good DX criteria still include the consequences of technical decisions, such as difficulty level, package size and barriers to use or contribute.</p><p>Please value pure simplicity and avoid unnecessary complexity. Sometimes, we really need new tools to scale the project. But make sure to question if that’s really necessary. For example, if it is possible to write CSS without any frameworks, write it — it is more feasible than it looks. Each layer that we add to the stack can create a barrier for those who don’t have context of that specific technology; we are often not aware of that, because it looks familiar to us. It’s a matter of empathy and inclusion, but also of allowing more people access to your project, by using or contributing.</p><p>Try your best not to weigh down your project with dependencies. Each of them requires updates in the future, which can break the project and generate work to adapt it, in addition to being a potential door for vulnerabilities. Don’t lose control.</p><p>Keep trying to automate as many manual processes as you can. For example, instead of asking to import typographic fonts or icons manually, include them in the project package and create simple ways to call these assets. Aim for the concept of “zero configuration”.</p><p>Test the speed to download and run the project, and look for improvements in this process as well.</p><h4>4. Update guides</h4><p>Astro once released version 2.0.0 with breaking changes — that is, with incompatible changes that can cause breaks in the projects where the dependency is installed. In that case, the reason was that some CSS classes and some icon names were changed.</p><p>Updating a dependency in these conditions requires careful adjustments to the project in order to avoid unpleasant surprises. What can you do to improve DX?</p><ul><li>Always be mindful of changes that can cause breakage and weigh the benefits before proceeding. Plan the new version to isolate the incompatibility and cause minimal side effects;</li><li>When you release this version (which will be <em>major</em>, according to <a href="https://semver.org/">Semantic Versioning</a>), write an Update Guide mapping all the changes that developers need to make to their projects that use the design system. <a href="https://github.com/magnetis/astro/blob/master/UPDATE_GUIDE_2_0_0.MD">See Astro’s v2.0.0 Update Guide</a> here as an example.</li></ul><p>In conclusion, a design system (or any project) with good DX is a system that’s easy and pleasant to use and contribute. With equal parts of technical quality and clear communication, it is possible to create an experience that generates less stress and makes life easier for developers on your team, and even for other teams out there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165825b12cda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/dx-developer-experience-in-design-systems-165825b12cda">DX: Developer Experience in Design Systems</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Pills: spread operator and rest parameter]]></title>
            <link>https://medium.com/larimaza-en/javascript-pills-spread-operator-and-rest-parameter-b1d0cb20cdd4?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1d0cb20cdd4</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 19:31:31 GMT</pubDate>
            <atom:updated>2019-11-22T19:31:58.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*BeqMOdiw5N5HE7IR" /><figcaption>Photo by The Creative Exchange</figcaption></figure><p><a href="https://medium.com/magnetis-backstage/p%C3%ADlulas-de-javascript-operador-spread-e-par%C3%A2metro-rest-afd1f0266036"><em>[clique aqui para português]</em></a></p><p><em>This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!</em></p><p>Among the numerous new features of ES6 is a new and useful operator. The <strong>spread</strong> operator, represented by the three-dot ellipsis ..., allows you to distribute the content of any <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterable object</a> into multiple elements.</p><p>For starters, a simple way to test this operator’s behavior is to use it just before a variable and log the result into the console. Let’s apply it to an array:</p><pre>const names = [&#39;Lestat&#39;, &#39;Marius&#39;, &#39;Akasha&#39;];</pre><pre>console.log(...names);<br><em>// Lestat Marius Akasha</em></pre><p>Note that the array has been separated, or <em>spread</em>, element by element.</p><p>The utilities of the <strong>spread</strong> operator in practice are broad. One of them is the possibility of combining arrays. See the example below:</p><pre>const males = [&#39;Lestat&#39;, &#39;Louis&#39;, &#39;Marius&#39;];<br>const females = [&#39;Pandora&#39;, &#39;Akasha&#39;];</pre><pre>const characters = [...males, ... females];</pre><pre>console.log(characters);<br><em>// [&#39;Lestat&#39;, &#39;Louis&#39;, &#39;Marius&#39;, &#39;Pandora&#39;, &#39;Akasha&#39;]</em></pre><p>The end result stored in the variable characters is an array that combines the values ​​of the arrays males and females.</p><p>There is also a variation of this operator: the <strong>rest</strong> parameter. If we think of the <strong>spread</strong> operator as someone who takes elements out of a box and spreads them elsewhere, we might say that the <strong>rest</strong> parameter does the opposite: it collects scattered elements and stores them in a box.</p><p>The <strong>rest</strong> parameter syntax is also an ellipses ... and it allows us to represent an indefinite number of elements as an array. Let’s clarify this with an example:</p><pre>const author = [&#39;Anne Rice&#39;, 1941, &#39;USA&#39;, &#39;Interview With The Vampire&#39;, &#39;The Vampire Lestat&#39;, &#39;The Queen of the Damned&#39;];</pre><pre>const [name, birth, country, ...books] = author;</pre><pre>console.log(name);<br><em>// Anne Rice</em></pre><pre>console.log(birth);<br><em>// 1941</em></pre><pre>console.log(country);<br><em>// USA</em></pre><pre>console.log(books);<br><em>// [&#39;Interview With The Vampire&#39;, &#39;The Vampire Lestat&#39;, &#39;The Queen of the Damned&#39;]</em></pre><p>Here, we use <a href="https://medium.com/larimaza-en/javascript-pills-destructuring-4675e4867451">destructuring</a> to retrieve the values ​​from the array author and assign them to isolated variables. Following the order of the elements, name, birth and country get the first three values ​​of the array, while books gets the rest (hence <strong>rest</strong>!) formatted as an array.</p><p>And finally, we can also use the <strong>rest</strong> parameter to represent an indefinite number of arguments in a <a href="https://en.wikipedia.org/wiki/Variadic_function">variadic function</a> — that is, a function that takes an infinite number of parameters.</p><p>Let’s use it to create a function that sums up any amount of numbers and returns the result:</p><pre>function sum (...numbers) {<br>  let result = 0;<br>  for(const number of numbers) {<br>    result += number;<br>  }<br>  return result;<br>}</pre><p>We can now call the sum() function with any number of parameters:</p><pre>sum(1, 2);<br><em>// 3</em></pre><pre>sum(1, 10, 100, 100);<br><em>// 1111</em></pre><p>That&#39;s all for today and see you next time ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1d0cb20cdd4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/javascript-pills-spread-operator-and-rest-parameter-b1d0cb20cdd4">JavaScript Pills: spread operator and rest parameter</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Pills: destructuring]]></title>
            <link>https://medium.com/larimaza-en/javascript-pills-destructuring-4675e4867451?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4675e4867451</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Wed, 13 Nov 2019 22:11:45 GMT</pubDate>
            <atom:updated>2019-11-13T22:15:01.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*NypbDInUSW5kNYjg" /><figcaption>Photo by Florian Klauer</figcaption></figure><p><a href="https://medium.com/magnetis-backstage/p%C3%ADlulas-de-javascript-desestrutura%C3%A7%C3%A3o-33d9bada18e7"><em>[clique aqui para português]</em></a></p><p><em>This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!</em></p><p>ES6 brought a new way to extract data from arrays and objects to different variables called <strong>destructuring</strong>. Before that, extracting from an array was done like this:</p><pre>const ages = [14, 28, 47];<br><br>const age1 = ages[0];<br>const age2 = ages[1];<br>const age3 = ages[2];<br><br>console.log(age1, age2, age3);<br>// 14 28 47</pre><p>And extracting from an object was done like this:</p><pre>const person = {<br>  name: &#39;Barbara&#39;,<br>  age: 36,<br>  job: &#39;Developer&#39;<br>};<br><br>const name = person.name;<br>const age = person.age;<br>const job = person.job;<br><br>console.log(name, age, job);<br>// Barbara 36 Developer</pre><p>Destructuring accomplishes the same task, but in a simpler and leaner way. Let’s go back and refactor the first example using this technique:</p><pre>const ages = [14, 28, 47];<br><br>const [age1, age2, age3] = ages;<br><br>console.log(age1, age2, age3);<br>// 14 28 47</pre><p>Wow, we turned three lines of code into one!</p><p>Observe the syntax of the second line, which is where the destructuring happens. On the left side, we use square brackets to indicate that we are destructuring an array; right there, we declare three variables at the same time, age1, age2, and age3, to save the extracted values. On the right side, we indicate that these values ​​shall be copied from the ages array.</p><p>We did not specify the indexes from which the values ​​should be extracted because they are no longer needed; now they implicitly follow the order of the elements in the array.</p><p>However, this does not mean we have to extract all values. You can ignore values ​​by leaving a blank space between commas, like this:</p><pre>const ages = [14, 28, 47];<br><br>const [age1, , age2] = ages;<br><br>console.log(age1, age2);<br>// 14 47</pre><p>In the example above, destructuring skipped the second index, which was dropped.</p><p>We can follow the same logic to extract values ​​from an object. Let’s try destructuring our previous object example:</p><pre>const person = {<br>  name: &#39;Barbara&#39;,<br>  age: 36,<br>  job: &#39;Developer&#39;<br>};<br><br>const {name, age, job} = person;<br><br>console.log(name, age, job);<br>// Barbara 36 Developer</pre><p>Here, the curly braces {} indicate that the object will be destructured and the values ​​will be stored in the name, age and job variables. And on the right side, we state that the values ​​will be copied from the person object.</p><p>We did not specify the keys from which the values ​​should be extracted because, by naming the variables identically to the object keys, we let the destructuring match them and automatically store the value of the key name in the variable name. It’s like doing const name = person.name.</p><p>It&#39;s worth noting that this operation does not alter the original array or object — it just copies its values ​​to other variables.</p><p>That’s all for today and see you next time ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4675e4867451" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/javascript-pills-destructuring-4675e4867451">JavaScript Pills: destructuring</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Pills: var, let and const]]></title>
            <link>https://medium.com/larimaza-en/javascript-pills-var-let-and-const-78a7f29af82f?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a7f29af82f</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 17:21:13 GMT</pubDate>
            <atom:updated>2019-10-30T17:21:13.757Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*X_9vOe1_JxawpI4-" /><figcaption>Photo by Samuel Zeller</figcaption></figure><p><a href="https://medium.com/magnetis-backstage/p%C3%ADlulas-de-javascript-var-let-e-const-7970a853da13"><em>[clique aqui para português]</em></a></p><p><em>This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!</em></p><p>Today, we have three keywords for declaring variables in JavaScript: var, let and const. The keyword var has always been around, but let and const are ES6 additions. The last two have virtually eliminated the need for var, which has lately become discouraged. Let’s find out why!</p><p>The main highlight of using const is that this type of variable, as the name implies, is constant: it cannot be redeclared and its value cannot be <strong>reassigned</strong> (this does not mean it is immutable; it can still change through other manipulations). Therefore, the value of every const must be assigned in the same statement as it was declared, since we cannot assign it later. Here’s what happens when we try to perform an illegal reassignment:</p><pre>const juice = &#39;orange&#39;;</pre><pre>juice = &#39;apple&#39;;<br><em>// Error: Assignment to constant variable</em></pre><p>However, it is worth noting that, because it&#39;s not immutable, if const keeps an object, its <strong>keys and values</strong> ​​can be changed normally:</p><pre>const myObj = { juice: &#39;orange&#39; };</pre><pre>myObj.juice = &#39;apple&#39;;</pre><pre>myObj.juice<br><em>// &#39;apple&#39;</em></pre><p>Another difference between the three is that declaring a global variable (i.e. outside of a function) with var automatically adds it as a property of the window object:</p><pre>var coffee = &#39;black&#39;;</pre><pre>window.coffee === coffee<br><em>// true</em></pre><p>However, declaring a global variable with let or const does not add it to the window object:</p><pre>let tea = &#39;green&#39;;</pre><pre>window.tea === tea<br><em>// false</em></pre><p>In addition, both let and const declare a local variable within the scope of the block they are inserted into — unlike var, which ignores the block unless it is a function. A block is considered to be any brace {} delimited space. Here&#39;s an example of how let behaves in the scope of an if block:</p><pre>let myNumber = 1;</pre><pre>if (myNumber === 1) {<br>  let myNumber = 2;</pre><pre>  console.log (myNumber);<br><em>  // 2</em><br>}</pre><pre>console.log (myNumber);<br><em>// 1</em></pre><p>If we look it up from within the if block, the value of myNumber is the one that was assigned inside that block: 2. But if we reference it from outside the block, we have no access to the value that was assigned within it, since the variable is only available in that scope. We can only see the outside value of myNumber, attributed back at the example&#39;s first line: 1.</p><p>The same behaviour applies to const:</p><pre>const myNumber = 1;</pre><pre>if (myNumber === 1) {<br>  const myNumber = 2;</pre><pre>  console.log (myNumber);<br>  <em>// 2</em><br>}</pre><pre>console.log (myNumber);<br><em>// 1</em></pre><p>This difference between scopes also affects the <strong>hoisting</strong> of the variables. Any variables declared with var are hoisted to the top of the function scope in which they were declared (or the global scope if they are not within any function). This means that the declaration (for example, var a) is executed before any other code, and even before the value is assigned:</p><pre>function getMood (isHappy) {<br>  if (isHappy) {<br>    var happy = &#39;Yay!&#39;;<br>  } else {<br>    var meh = &#39;Meh&#39;;<br>  }<br>}</pre><p>In the above function, if we analyse the hoisting of the variables, this is what is happening in practice:</p><pre>function getMood (isHappy) {<br>  var happy, meh;</pre><pre>  if (isHappy) {<br>    happy = &#39;Yay!&#39;;<br>  } else {<br>    meh = &#39;Meh&#39;;<br>  }<br>}</pre><p>Can you imagine how this behaviour can return many accidental undefined&#39;s (and migraines)?</p><p>Here comes a big advantage of the let and const variables: because they consider the block in which they were declared as their scope, they behave differently. If the variable is declared within a block, it is suspended in the “temporal dead zone” until the declaration is processed, instead of being hoisted to the top. Ergo, the variable can only be accessed after its declaration. Sounds safer, right?</p><p>We can link this context to yet another particularity of let and const: they cannot be redeclared in the same scope and any attempt returns a syntax error. However, redeclaration at different scopes is accepted, because one context does not see the other. Here’s an example of valid code with let foo declared in two different blocks:</p><pre>let myValue = 1;</pre><pre>switch (myValue) {<br>  case 0: {<br>    let foo;<br>    break;<br>  }<br>  case 1: {<br>    let foo;<br>    break;<br>  }<br>}</pre><p>When should we use each type of variable, then?</p><p>The decision between let and const depends only on whether you intend to reassign the value of this variable. Using const even improves the readability of your code by making it clear that such a variable is a constant.</p><p>In general: scoping, the ability to prevent value reassignment and the consequent reduced freedom in JavaScript (considered excessive by some) makes the use of let and const preferred by developers today to prevent accidental changes and breakage. The general convention is that there is no reason to use var anymore.</p><p>Keep in mind that there are still other differences and more advanced features. If you&#39;d like to dive deeper, you should refer to the MDN specifications for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a>.</p><p>That’s all for today and see you next time ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a7f29af82f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/javascript-pills-var-let-and-const-78a7f29af82f">JavaScript Pills: var, let and const</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Pills: call and apply]]></title>
            <link>https://medium.com/larimaza-en/javascript-pills-call-and-apply-c68b4ee2a1c6?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c68b4ee2a1c6</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Tue, 15 Oct 2019 22:38:36 GMT</pubDate>
            <atom:updated>2019-10-15T22:38:36.758Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*SukesqhT8lxQFbiJ" /><figcaption>Photo by William Krause</figcaption></figure><p><a href="https://medium.com/magnetis-backstage/p%C3%ADlulas-de-javascript-call-e-apply-f98dce3a1988"><em>[clique aqui para português]</em></a></p><p><em>This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!</em></p><p>call() and apply() are very similar methods both used to pass a specific value of this to a function. They make it possible to determine the context from which the function will be executed.</p><p>Both methods can be invoked directly from a function. As an argument, we pass the object we want to use as the value of this; we may also pass other arguments that the function receives, if any. Consider the function and the object below:</p><pre>function sayHello() {<br>  console.log(&#39;Hello, &#39; + this.name);<br>}</pre><pre>const user1 = {<br>  name: &#39;Paula&#39;,<br>  hobby: &#39;witchcraft&#39;<br>}</pre><p>If we want to apply the sayHello function to the context of the user1 object, we can do so with call(). We will <strong>not</strong> call the sayHello() function! We&#39;ll just reference it by name and then use dot notation to invoke the call() function method, passing the user1 object as an argument, which is the value of this we want to use. Let’s test this:</p><pre>sayHello.call(user1);</pre><pre><em>// &#39;Hello, Paula&#39;</em></pre><p>Observe where the parentheses responsible for making the invocation are: the call() method executes the function, looking inside the user1 object to find the this.name value. At this point, the expression this.name is replaced by user1.name, which in turn is replaced by &#39;Paula&#39;.</p><p>Now, let’s make things a little more interesting! Let’s test call() on a function that takes arguments:</p><pre>function commentHobby(opinion) {<br>  console.log(&#39;I &#39; + opinion + &#39; &#39; + this.hobby);<br>}</pre><pre>const user1 = {<br>  name: &#39;Paula&#39;,<br>  hobby: &#39;witchcraft&#39;<br>}</pre><p>In addition to passing the user1 object again as the value of this, now we&#39;ll also pass the argument received by the commentHobby function to the call() argument list. Observe:</p><pre>commentHobby.call(user1, &#39;love&#39;);</pre><pre><em>// &#39;I love witchcraft&#39;</em></pre><p>The result is exactly the same; the call() method invoked the commentHobby function using user1 as the value of this. This time, however, we also passed the &#39;love&#39; string to replace the opinion argument.</p><p>What if we tried to use the call() method on a function that&#39;s inside an object — that is, a <strong>method</strong>? Yes: we can borrow a method from an object and apply it to another one!</p><p>Let’s create the kitty object and the puppy object:</p><pre>const kitty = {<br>  race: &#39;cat&#39;,<br>  color: &#39;white&#39;,<br>  greet: function() {<br>    console.log(&quot;Hi, I&#39;m a &quot; + this.race);<br>  }<br>}</pre><pre>const puppy = {<br>  race: &#39;dog&#39;,<br>  color: &#39;black&#39;<br>}</pre><p>If we test the greet method as it is now, the value of this is the kitty object and therefore this.race is replaced with its value &#39;cat&#39;:</p><pre>kitty.greet();</pre><pre><em>// &quot;Hi, I&#39;m a cat&quot;</em></pre><p>But if we have to borrow the greet method to apply to the puppy object, we can access the method from within the kitty object and use call() to invoke it in the puppy object:</p><pre>kitty.greet.call(puppy);</pre><pre><em>// &quot;Hi, I&#39;m a dog&quot;</em></pre><p>At this point you may be asking: but what about apply()? Well, apply() has the exact same role: to call a function using the provided value of this, plus any other arguments if applicable. The difference is that, instead of comma-separated arguments, apply() receives the additional function arguments in an <strong>array</strong>.</p><p>Let’s test it in a function with more than one argument:</p><pre>function sayWhere(city, country) {<br>  console.log (&#39;I am &#39; + this.name + &#39; from &#39; + city + &#39;, &#39; + country);<br>}</pre><pre>const user2 = {<br>  name: &#39;Lola&#39;<br>}</pre><p>Let&#39;s see what happens if we use apply() to apply the sayWhere function to the context of the user2 object, while also passing the arguments received by sayWhere in an array:</p><pre>sayWhere.apply(user2, [&#39;Paris&#39;, &#39;France&#39;]);</pre><pre><em>// &#39;I am Lola from Paris, France&#39;</em></pre><p>The use is very similar, isn’t it? When should we choose call() or apply(), then?</p><p>This depends on the type of arguments required in the function we want to use. apply() is especially useful when a function takes many arguments, or yet when we are not sure how many arguments exactly it will receive.</p><p>That’s all for today and see you next time ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c68b4ee2a1c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/javascript-pills-call-and-apply-c68b4ee2a1c6">JavaScript Pills: call and apply</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Pills: immediately invoked function expression (IIFE)]]></title>
            <link>https://medium.com/larimaza-en/javascript-pills-immediately-invoked-function-expression-iife-d61ce47e5b42?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61ce47e5b42</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Thu, 10 Oct 2019 00:43:59 GMT</pubDate>
            <atom:updated>2019-10-10T00:43:59.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*LPTPta08al0BoHd9" /><figcaption>Photo by Zoltan Tasi</figcaption></figure><p><a href="https://medium.com/magnetis-backstage/p%C3%ADlulas-de-javascript-express%C3%A3o-de-fun%C3%A7%C3%A3o-invocada-imediatamente-iife-7b2a2cee209f"><em>[clique aqui para português]</em></a></p><p><em>This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!</em></p><p>An <strong>immediately invoked function expression</strong>, or IIFE, is a function called immediately after it is declared.</p><pre>(function helloWorld() {<br>    alert(&#39;Hello, world!&#39;);<br>  }<br>)();</pre><pre><em>// alert &#39;Hello, world!&#39;</em></pre><p>In the example above, we wrap the function declaration in parentheses and add another pair of parentheses at the end, thus invoking the function immediately. We can also create an IIFE with an anonymous function:</p><pre>(function() {<br>    alert(&quot;What&#39;s up?&quot;);<br>  }<br>)();</pre><pre><em>// alert &quot;What&#39;s up?&quot;</em></pre><p>As we would when calling any function, we can also use the last pair of parentheses to enter arguments, like the example below:</p><pre>(function(message) {<br>    alert(message);<br>  }<br>)(&quot;Let&#39;s go!&quot;);</pre><pre><em>// alert &quot;Let&#39;s go!&quot;</em></pre><p>One of the main perks of the IIFE is that it can use its scope to create closure and prevent data inside it from being accessed. In practice, it works like this:</p><pre>const myFunction = (<br>  function() {<br>    const password = 1337;</pre><pre>    return function() {<br>      console.log(password);<br>    }<br>  }<br>)();</pre><pre><em>// 1337</em></pre><p>The function is executed immediately, as it is an IIFE. It returns an anonymous function, which is stored in myFunction and captures (or focuses) the password variable. This means that it holds the reference to its parent scope, like every nested function does.</p><p>Now we have in myFunction a private mutable state that cannot be accessed from outside the function. However, when we do console.log from within the returned function, we can access the password value!</p><p>There is also a different syntax for IIFE. We can move the second pair of parentheses into the first pair, thus wrapping the entire expression with the first pair of parentheses:</p><pre>(function bark() {<br> alert(&#39;Woof!&#39;);<br>} ());</pre><p>This is just a style choice, as the result is identical.</p><p>It is noteworthy that placing these variables in closed scopes not only has its advantages in data security; if fewer variables are created globally, we reduce the noise and chance of conflicting their names.</p><p>That’s all for today and see you next time ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61ce47e5b42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/javascript-pills-immediately-invoked-function-expression-iife-d61ce47e5b42">JavaScript Pills: immediately invoked function expression (IIFE)</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Pills: function that returns another function]]></title>
            <link>https://medium.com/larimaza-en/javascript-pills-function-that-returns-another-function-9378e8db04f8?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9378e8db04f8</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Mon, 07 Oct 2019 22:58:20 GMT</pubDate>
            <atom:updated>2019-10-07T22:58:20.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/994/0*b3VRVKpJBwk1M4Y9.jpeg" /><figcaption>Photo by TheThinkSomeMoreStore</figcaption></figure><p><a href="https://medium.com/magnetis-backstage/p%C3%ADlulas-de-javascript-fun%C3%A7%C3%A3o-que-retorna-outra-fun%C3%A7%C3%A3o-a9c5489f14fd"><em>[clique aqui para ler em português]</em></a></p><p><em>This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!</em></p><p>A function that returns another function is a type of <strong>higher order function</strong>. Observe the example below:</p><pre>function outerFunction() {<br>  alert(&#39;Hello!&#39;);</pre><pre>  return function() {<br>    alert(&#39;Can you hear me?&#39;);<br>  };<br>}</pre><p>Despite what it may seem, if we simply call the outer function with outerFunction(), we will only see the first alert &#39;Hello!&#39;; the inner function code will not be executed. We’ll need a specific trick if we want to trigger the second alert!</p><p>There are two ways to execute the returned function. One option is storing the external function outerFunction in a variable. Behind the curtains, we are actually storing the<strong> return </strong>of the function this way:</p><pre>const innerFunction = outerFunction();</pre><p>Now, we can call this new variable like any other function and only the returned function will be executed:</p><pre>innerFunction();<br>// alert &#39;Can you hear me?&#39;</pre><p>Another alternative is calling the function immediately, without the need to create a variable. Just add another set of parentheses to the external function call:</p><pre>outerFunction()();<br>// alert &#39;Hello!&#39; and then alert &#39;Can you hear me?&#39;</pre><p>Note that the effect in this case is different from the first example. Here, the first pair of parentheses executes the outerFunction function and returns the inner function, which is then called by the second pair of parentheses!</p><p>We must choose an approach by assessing whether or not we want to execute the external function content before the returned function content is executed.</p><p>That’s all for today and see you next time ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9378e8db04f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/javascript-pills-function-that-returns-another-function-9378e8db04f8">JavaScript Pills: function that returns another function</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Pills: accessing object keys using external variables]]></title>
            <link>https://medium.com/larimaza-en/javascript-pills-accessing-object-keys-using-external-variables-6e15e85f126a?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e15e85f126a</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Sun, 06 Oct 2019 23:18:41 GMT</pubDate>
            <atom:updated>2019-10-06T23:18:41.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*qguhb_RgeiDsTAid" /><figcaption>Photo by CMDR Shane</figcaption></figure><p><a href="https://medium.com/magnetis-backstage/p%C3%ADlulas-de-javascript-acessando-chaves-de-um-objeto-usando-vari%C3%A1veis-externas-2479d20864d"><em>[clique aqui para ler em português]</em></a></p><p><em>This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!</em></p><p>Consider an object called shirt with a key named color storing the string &#39;blue&#39;:</p><pre>const shirt = {</pre><pre>  color: &#39;blue&#39;</pre><pre>}</pre><p>If we had to access the value of color, we could either use the bracket notation shirt[&#39;color&#39;] or the dot notation shirt.color. Both choices are equivalent, right? Hold that thought!</p><p>Let’s now create a variable and save the string &#39;color&#39; inside it:</p><pre>const myVariable = &#39;color&#39;;</pre><p>Now, we can also use this variable to access the color value within the shirt object. We will first try the bracket notation. Watch this:</p><pre>shirt[myVariable];</pre><pre>// &#39;blue&#39;</pre><p>This is possible because, when executing this code, the myVariable variable is replaced with its content, which is the string &#39;color&#39;. In practice, we are doing shirt[&#39;color&#39;].</p><p>Ok, that makes sense! But just out of curiosity, let’s try this same type of access using the dot notation?</p><pre>shirt.myVariable;</pre><pre>// undefined</pre><p>…Uh, what? Undefined? What happened here?</p><p>It gets easy to spot the difference between both scenarios if you know this basic concept about JavaScript objects: underneath the curtain, all keys in an object are strings, even when the quotation marks are omitted — which is our case.</p><p>When running shirt.myVariable, we are requesting JavaScript to find a key inside shirt which corresponds to the string &#39;myVariable&#39;, which doesn’t exist. In practice, that was exactly the same as doing shirt[&#39;myVariable&#39;].</p><p>However, if you go back to using the bracket notation with shirt[myVariable], JavaScript doesn’t coerce (convert) the bracket contents into a string and looks for the variable instead — which is the behavior we expect.</p><p>That’s all for today and see you next time ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e15e85f126a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-en/javascript-pills-accessing-object-keys-using-external-variables-6e15e85f126a">JavaScript Pills: accessing object keys using external variables</a> was originally published in <a href="https://medium.com/larimaza-en">Lari Maza | En</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DX: Developer Experience em Design Systems]]></title>
            <link>https://medium.com/larimaza-pt/dx-developer-experience-em-design-systems-1ff507f216ee?source=rss-5531a5a889f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ff507f216ee</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[dx]]></category>
            <category><![CDATA[desenvolvimento-software]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Lari Maza]]></dc:creator>
            <pubDate>Fri, 16 Aug 2019 15:09:48 GMT</pubDate>
            <atom:updated>2020-01-28T23:31:19.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Desenvolvedora sentada pensando na frente do computador" src="https://cdn-images-1.medium.com/max/1024/1*M58pCJTTiydxmELyhSPMPQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@joeel56">Nicole Wolf</a></figcaption></figure><p><a href="https://medium.com/larimaza-en/dx-developer-experience-in-design-systems-165825b12cda"><em>[click here for English]</em></a></p><p>DX, ou Developer Experience, é uma disciplina que descreve a experiência de uma pessoa desenvolvedora ao utilizar um produto. De forma análoga à UX (User Experience), uma boa DX faz toda a diferença na aceitação e no potencial de divulgação do seu produto, seja ele uma API, uma biblioteca, uma ferramenta ou um serviço. A conscientização sobre esse assunto tem crescido tanto que já existe até trabalho especializado — a bio do Twitter da dev <a href="https://medium.com/u/c2509fce86ff">Sarah Drasner</a> diz &quot;<em>Head of DX @ </em><a href="https://medium.com/u/5250f9d9bd2f"><em>Netlify</em></a>&quot;.</p><p>Na minha experiência desenvolvendo o <a href="http://astro.magnetis.com.br/">Astro</a>, design system da <a href="https://medium.com/u/21c4968105a4">Magnetis</a>, a qualidade da DX é bastante relevante para impulsionar a produtividade do cliente interno. Essas pessoas podem ou não ser colaboradoras da Magnetis, uma vez que o Astro é open source — o que significa que a responsabilidade é ainda maior.</p><p>Com base nesse aprendizado, trago alguns pontos de atenção para melhorar a DX do seu projeto:</p><h4>1. Documentação</h4><p>Parece até um pouco óbvio mencionar a documentação como um ponto principal de atenção na DX; mas, para um texto que muitas vezes será a única via de comunicação com a pessoa usuária, ele raramente recebe a atenção que merece.</p><p>Em projetos e repositórios abertos ou fechados, alguns mantenedores esperam que os usuários entendam tudo apenas lendo o código — o que não só é uma comunicação ruim, mas também uma falha de empatia. E dentro de times, a solução para projetos mal documentados muitas vezes é perguntar pra alguém, o que também é ruim para ambos os lados.</p><p>A documentação é sua oportunidade de explicar com linguagem humana a finalidade e a forma de uso do seu projeto. Aqui, você deve ensinar a usar o design system, mas também a contribuir para o código dele (ainda que não seja open source, novas pessoas podem vir trabalhar no projeto a qualquer momento). Pense nesses momentos separadamente — você pode até criar dois arquivos separados no GitHub, como fizemos no <a href="https://github.com/magnetis/astro">repositório do Astro</a> com &quot;Readme&quot; (guia de uso) e &quot;Contributing&quot; (guia de contribuição).</p><p>Não entrarei em detalhes sobre como escrever uma boa documentação porque <a href="https://medium.com/magnetis-backstage/como-escrever-boas-documenta%C3%A7%C3%B5es-b36131d78f7c">já escrevi um artigo sobre isso</a>, mas, em resumo, ela deve contemplar esses três A&#39;s:</p><ul><li><strong>A</strong>brangente: Certifique-se de que o documento cobre todas as dúvidas que possam surgir sobre como funciona o projeto. Explique o que ele faz, como instalar, como usar, e inclua soluções de problemas conhecidos. Seu objetivo aqui é anular a necessidade de te contatar diretamente pra tirar dúvidas. Não seja um gargalo. A fonte da verdade (<em>Single Source of Truth</em>) deve ser a documentação, e não você.</li><li><strong>A</strong>cessível: Não assuma que toda pessoa que ler o documento tem o mesmo nível técnico que você, mesmo que você ache que tem um nível técnico baixo (alô, síndrome do impostor!). Evite termos técnicos quando possível. Escreva tutoriais passo a passo. Não assuma que a pessoa sabe clonar um projeto ou instalar dependências via terminal, por exemplo. Explique para um iniciante e você estará explicando para todo mundo.</li><li><strong>A</strong>migável: Ler documentação pode ser uma atividade maçante, então tente não deixá-la desnecessariamente longa. Existe uma diferença entre abrangente e prolixo. Vá direto ao ponto, use um tom amigável e, se quiser, pode até incluir um toque de humor.</li></ul><h4>2. Padrões de uso</h4><p>No caso do Astro, o design system é utilizado aplicando classes CSS a uma estrutura de markup exemplificada na documentação. Eis um exemplo abaixo:</p><figure><img alt="Print da documentação do Astro mostrando os botões renderizados e, abaixo, o exemplo do markup e estrutura de classes CSS" src="https://cdn-images-1.medium.com/max/1024/1*0CrwvuEwQkbe203Y7mWbDw.png" /><figcaption>Botões do Astro e sua estrutura de markup e classes CSS</figcaption></figure><p>Tentamos criar nomes de classes que sejam descritivos para humanos, em vez de algo como a-bt--ur__md1, ainda que fiquem mais longos; queremos que sejam auto explicativos e memoráveis, o que diminui a confusão e a necessidade de consultar a documentação repetidamente.</p><p>Outro ponto importante é que os nomes de classe precisam ser mais específicos (como a-btn) em vez de totalmente genéricos (como btn) para evitar conflitos com o CSS existente em projetos legados. O objetivo aqui é gerar o mínimo de efeitos colaterais na importação do design system, e deve-se aplicar essa mentalidade a todos os pontos do projeto que se possa identificar.</p><p>Por fim, para criar um sistema escalável e previsível, é preciso tentar manter um padrão de uso que faça sentido. Esse é um grande desafio quando recebemos demandas de design que fogem à norma, e pode ser necessário negociar para satisfazer essas demandas enquanto se mantém também a consistência.</p><p>Por exemplo: no Astro, temos muitas variantes de estilos de botões e cada uma delas tem quatro cores. O design system tende a escalar, e, quando introduzirmos novas cores ou estilos, queremos seguir o padrão e até tentar facilitar a manipulação desses botões com menos consultas à documentação.</p><p>Para isso, criamos uma estrutura de classes que variam de forma previsível. a-btn--uranus é o botão primário na cor azul (que nomeamos &quot;<em>uranus</em>&quot;). Nas outras variantes, acrescentamos um modificador que pode ser a-btn--outline-uranus para o botão outline ou a-btn--ghost-uranus para o botão ghost.</p><p>Além disso, a cor &quot;<em>uranus</em>&quot; pode ser trocada por qualquer uma das outras variantes (&quot;<em>mars</em>&quot; pra vermelho, &quot;<em>venus</em>&quot; pra rosa ou &quot;<em>earth</em>&quot; pra verde) em qualquer um dos botões, que o resultado é previsível.</p><p>E para definir o tamanho, acrescentamos obrigatoriamente uma das três classes de tamanho: a-btn--small, a-btn--medium ou a-btn--large. Independente de qual for o botão, o resultado é sempre o mesmo.</p><p>Eis um vídeo demonstrando a troca desses modificadores (abra em uma nova aba):</p><p><a href="https://drive.google.com/file/d/1FlsoZ0plt9oqnPxlWyxD0_p1ILq6PNX_/preview">demo.webm</a></p><p>Criando padrões e previsibilidade, o uso fica mais intuitivo, à prova de erros e diminui a dependência da documentação.</p><h4>3. Tecnologias</h4><p>Além dos pontos que cobrimos, nos critérios de uma boa DX ainda pesam as consequências das decisões técnicas, como a facilidade de uso, o peso do pacote e as barreiras para utilizar e contribuir.</p><p>Tente prezar pela simplicidade pura e evitar complexidade desnecessária. Às vezes, precisamos mesmo de novas ferramentas para escalar o projeto. Mas não deixe de questionar se aquilo é mesmo necessário. Por exemplo, se for possível escrever CSS sem nenhum framework, escreva — é mais viável do que parece. Cada camada que acrescentamos na stack, ainda que nos pareça familiar, pode criar uma barreira para quem não tiver contexto daquela tecnologia específica. É uma questão de empatia e inclusão, mas também de permitir que mais pessoas se agreguem ao seu projeto, usando ou contribuindo.</p><p>Faça o seu melhor para não lotar seu projeto de dependências. Cada uma delas requer atualizações no futuro, o que pode quebrar o projeto e gerar trabalho para adaptá-lo, além de ser uma potencial porta para vulnerabilidades. Não perca o controle.</p><p>Continue tentando automatizar todos os processos manuais que você conseguir. Por exemplo, em vez de pedir para importar fontes tipográficas ou ícones manualmente, inclua-os no pacote do projeto e crie formas simples de chamar esses assets. Tente aplicar o conceito de &quot;zero configuração&quot;.</p><p>Teste a velocidade para baixar e rodar o projeto, e busque melhorias nesse processo também.</p><p>Em resumo, um design system (ou qualquer projeto) com uma boa DX é um sistema fácil e agradável de usar e de contribuir. Com partes iguais de qualidade técnica e comunicação clara, é possível criar uma experiência que gere menos stress e facilite a vida de desenvolvedores no seu time, e até de outros times por aí afora.</p><p><em>Update em 28/9/19: Escreva um Guia de Atualização quando houver breaking changes</em></p><p>Recentemente, o Astro lançou a versão 2.0.0 com breaking changes — isso é, com alterações incompatíveis que podem causar quebras nos projetos em que a dependência está instalada. Nesse caso, o motivo é que mudamos algumas classes CSS e o nome de alguns ícones.</p><p>Atualizar uma dependência nessas condições requer atentas adequações no projeto para evitar surpresas desagradáveis. O que você pode fazer para melhorar a DX?</p><ul><li>Tenha sempre consciência de alterações que podem causar quebras e pese os benefícios antes de prosseguir. Planeje a nova versão de modo a isolar a incompatibilidade e causar o mínimo de efeitos colaterais;</li><li>Quando lançar essa versão (que será <em>major</em>, segundo o <a href="https://semver.org/">Semantic Versioning</a>), escreva um Guia de Atualização mapeando todas as alterações que os desenvolvedores precisam fazer em seus projetos que utilizam o design system. <a href="https://github.com/magnetis/astro/blob/master/UPDATE_GUIDE_2_0_0.MD">Veja o Update Guide da v2.0.0 do Astro aqui</a> como um exemplo.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ff507f216ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/larimaza-pt/dx-developer-experience-em-design-systems-1ff507f216ee">DX: Developer Experience em Design Systems</a> was originally published in <a href="https://medium.com/larimaza-pt">Lari Maza | PT-BR</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>